【问题标题】:Join two tables, select column based on value in first table连接两个表,根据第一个表中的值选择列
【发布时间】:2017-11-08 03:47:43
【问题描述】:

假设表 A 有两列“Type”和“Severity”,表 B 有列“Type”、“Severity_1”、“Severity_2”、“Severity_3”、“Severity_4”。

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

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

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

【问题讨论】:

  • "Severity_1", "Severity_2", ... 听起来像是一个糟糕的数据库设计;结果 if 通常是很多 If 语句来撤消损坏
  • 更好的设计是表 B 具有“类型”、“严重性”和“描述”列,并且每个严重性都有一行。
  • @dwilliss 这是另一家公司的产品,不幸的是我无法控制他们的数据库设计。
  • 就像 Plutonix 说的,一堆 If 语句。当然,您可以查询每个严重性案例(其中 A.Severity = 1 等)四次,然后连接结果?糟糕的设计会让人头疼。更好的是,如果你/他们可以的话,创建一个视图来扁平化 SQL 端的所有内容。
  • 表是否同时加入 A.Type = B.TypeA.Severity = n : Severity_n

标签: vb.net linq


【解决方案1】:

如果可能的话,你应该像这样制作一个视图

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 中查询视图。

【讨论】:

    猜你喜欢
    • 2015-10-15
    • 1970-01-01
    • 2021-04-28
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多