如何从2个表中将我的信息变为1行?

时间:2012-02-08 19:49:55

标签: sql database vb.net linq

Dim LocationList =
From rows In db.Locations, clientRow In db.Clients, stateData In db.Ref_States
Where rows.State = stateData.ID
Select ClientName = clientRow.Name, rows.ID, rows.Address1, rows.Address2, rows.City, StateName = stateData.Name, ShortStateName = stateData.ShortName, rows.ZipCode Order By Address1

这就是我所拥有的,这是非常错误的。一切都显示出来,但数据显示不正确,显示的行数多于存在的行数。

enter image description here

我想我可以拥有它,但你能查看我的代码并告诉我你是否看到任何问题?

        Dim LocationList =
        From rows In db.Locations, clientRow In db.Clients, stateData In db.Ref_States
        Where rows.State = stateData.ID And rows.ClientID = ucClientID And rows.ClientID = clientRow.ID
        Select ClientName = clientRow.Name, rows.ID, rows.Address1, rows.Address2, rows.City, StateName = stateData.Name, ShortStateName = stateData.ShortName, rows.ZipCode Order By Address1

1 个答案:

答案 0 :(得分:3)

这假设您的外键将Location.State映射到Ref_State.ID

Dim LocationList = From rows In db.Locations _
                   Join rs In Ref_State On rows.State Equals rs.ID _
                   Order By rows.Address1 _
                   Select rs.Name

以上回答了您原来的问题。添加Client表后,我会按如下方式编写查询:

Dim LocationList = _
    From clientRow In db.Clients _
    Join rows in db.Locations On clientRow.ID Equals rows.ClientID _
    Join db.stateData In Ref_States On rows.State Equals stateData.ID _ 
    Select ClientName = clientRow.Name, rows.ID, rows.Address1, rows.Address2, rows.City, StateName = stateData.Name, ShortStateName = stateData.ShortName, rows.ZipCode _
    Order By Address1

使用连接明确地编写它使我认为它更具可读性。