加入两个表,根据第一个表中的值选择列

时间:2017-11-07 15:38:27

标签: vb.net linq

想象一下有两列的表A" Type"和"严重性"和表B,列为"类型"," Severity_1"," Severity_2"," Severity_3&#34 ;," Severity_4"。

A.Severity是一个整数,所有B.Severity_ *字段都包含描述。

我想查询表A的类型和严重性,并返回第三列,其中包含表B中的相应描述。

目前,我使用LINQ并在select子句中有一组嵌套的IF语句。有没有办法投影表B或选择每个{Type,Severity,Severity_ *}记录并结合结果?

1 个答案:

答案 0 :(得分:0)

如果可能的话,您应该像这样

select a.Type, a.Severity,
case a.Severity
when 1 then b1.Severity_1
when 2 then b2.Severity_2
when 3 then b3.Severity_3
when 4 then b4.Severity_4
end as Description
from TableA a
left join tableb b1 on a.Severity = 1 and a.Type = b1.Type
left join tableb b2 on a.Severity = 2 and a.Type = b2.Type
left join tableb b3 on a.Severity = 3 and a.Type = b3.Type
left join tableb b4 on a.Severity = 4 and a.Type = b4.Type

然后只查询Linq中的视图。