簡體   English   中英

SQL:根據不同的條件選擇不同的列集顯示

[英]SQL: Selecting different set of columns to be displayed according to different conditions

我有六個表,如下所示: 表

主鍵:ID

表名:Table_1, ..., Table_6

我在設置 case-when 語句來實現這個邏輯時遇到了麻煩:

select table_1.id, table_1.A,
case    
    when table_1.A = data1, then show columns B and C
    when table_1.A = data2, then show columns D, E and F
    when table_1.A = data3, then show columns B, C, D, E and F
    when table_1.A = data4, then show no columns
from table_1, ..., table_6
where
    table_1.id = table2.id and
    table_1.id = table3.id and
    table_1.id = table4.id and
    table_1.id = table5.id and
    table_1.id = table6.id and
    table1.A = <one of data1/data2/data3/data4>

基本上,ID 和 A 列總是需要存在,B 到 F 以 A 列中的數據為條件。

所以有兩個問題:1.這甚至可能嗎? 2. 如果是,怎么做?

您可以使用LEFT JOIN 不匹配的列將是NULL

select *
from table_1 t1 left join
     table_2 t2
     using (id) left join
     table_3 t3
     using (id) left join
     . . .;

如果你真的想改變結果集中返回的列,那么你需要使用動態 SQL。

如果你真的想逐行改變列數,那是不可能的。 這樣的結果集不是 SQL 結果集。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM