2013-03-11 154 views
1
SELECT column_a1,column_b1,column_c1,column_d1,column_e1,column_f1,column_g1 
FROM mytable WHERE id=12 AND detectcolumn=1 

UNION ALL 

SELECT column_a2,column_b2,column_c2,column_d2,column_e2,column_f2 
FROM mytable WHERE id=12 AND detectcolumn=2 

UNION ALL 

SELECT column_a3,column_b3,column_c3,column_d3,column_e3,column_f3,column_g3 
FROM mytable WHERE id=12 AND detectcolumn=3 

UNION ALL 

SELECT column_a4 from mytable WHERE id=12 AND detectcolumn=4 

UNION ALL 

SELECT column_a5 from mytable WHERE id=12 AND detectcolumn=5 

UNION ALL 

SELECT column_a6 from mytable WHERE id=12 AND detectcolumn=6 

UNION ALL 

SELECT column_a7 from mytable WHERE id=12 AND detectcolumn=7  

我應該如何將所有這些sql語句合併成一個單獨的sql語句。我想根據detectcolumn的值從mytable中獲取特定的列。加入多個sql語句

我試着使用UNION ALL,但它給錯誤ORA-01789:查詢塊有結果列的數目不正確

+0

每個聯盟選擇句子必須有相同的字段計數。你的工會不符合這個要求。試着解釋你將會得到什麼。 – AnatolyS 2013-03-11 10:15:45

+0

我想從** mytable **獲取特定列,具體取決於** detectcolumn的值** – Akki 2013-03-11 10:17:18

+0

將此問題放在問題中,而不是作爲註釋 – 2013-03-11 10:17:37

回答

2

使用模式,如:

select 
    case detectcolumn 
    when 4 then column_a4 
    when 5 then column_a5 
    when 6 then column_a6 
    end 
from 
    my_table 
where 
    id   = 12 and 
    detectcolumn in (4,5,6) 
+0

如何在**之後提供多個欄名然後** – Akki 2013-03-11 10:36:38

+0

您需要哪些欄?請更新該問題以獲取更具體的信息 – 2013-03-11 11:37:49

+0

當** detectcolumn = 1時,我應該如何寫入多個列** – Akki 2013-03-11 11:42:19