【问题标题】:Select the same column value from 3 different tables from another value with the same line of code从具有相同代码行的另一个值中从 3 个不同的表中选择相同的列值
【发布时间】:2019-10-07 04:07:37
【问题描述】:

如何使用同一行代码从另一个值的 3 个不同表中选择相同的列值? 例如我有 3 个表:

  • table_one
  • table_two
  • table_three

它们都有相同的列名,比如“日期”。

table_main 有一个名为 type 的列,每行的值为 1 或 2 或 3。

如果 type 的值为 1,则表的名称必须是“table_one”,并且“日期”必须来自该表。

我想在同一行代码中从 table_$num 中选择“日期”,但 $num 需要来自“类型”以便

1 = one
2 = two
3 = three
SELECT table_main.id, table_main.type, table_$num.date 
FROM table_main 
   LEFT JOIN table_$num ON table_main.id = table_$num.id 
ORDER BY table_main.id ASC

【问题讨论】:

  • 请在您的问题中添加示例数据。
  • 这是一个非常糟糕的设计。您应该只有一个表而不是三个表,并且该表还应该有一个列 type

标签: sql select


【解决方案1】:
select  case
             when tm.type = 1 then tab_1.date
             when tm.type = 2 then tab_2.date
             when tm.type = 3 then tab_3.date
         end
      from table_main tm
 left join table_one tab_1 
        on tm.id = tab_1.id
 left join table_two tab_2 
        on tm.id = tab_2.id
 left join table_three tab_3 
       on tm.id = tab_3.id

按照您提供的代码,我假设 id 是关键列,因此加入该列。

希望这可能会有所帮助。

【讨论】:

    【解决方案2】:

    如果您想根据第一个表中的类型列有条件地join 到其他表,则使用left join -- 但在on 子句中包含条件:

    select coalesce(tab_1.date, tab_2.date, tab_3.date)
    from table_main tm
         table_one tab_1 
         on tm.id = tab_1.id and tm.type = 1 left join
         table_two tab_2 
         on tm.id = tab_2.id and tm.type = 2 left join
         table_three tab_3 
         on tm.id = tab_3.id and tm.type = 3
    

    【讨论】:

      猜你喜欢
      • 2017-12-24
      • 2019-05-31
      • 2022-01-01
      • 2020-12-20
      • 1970-01-01
      • 2017-02-14
      • 2012-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多