2013-06-18 73 views
0

是否有可能進行查詢,其執行以下操作SQL選擇值

選擇一個,b或c,d從表其中source = 2或目標= 2;

我想選擇A,B如果源= 2或c,d如果目標= 2。

這是可能的SQL語句?

+0

什麼是源和目標? –

+0

在什麼情況下你需要得到a和b或c和d?什麼情況? –

+0

呃...'SELECT ... FROM '?這是沒有意義的。你從*表*中選擇。你想從兩個不同的表中選擇嗎?如果是這樣,那通常可以使用'UNION'或'UNION ALL'。請提供(很多)更多細節。請參閱http://stackoverflow.com/tags/postgresql/info獲取有關提出更好問題的指導。無論如何,這與Java或Android有什麼關係? –

回答

2
select a,b 
from database 
where source = 2 

union 

select c,d 
from database 
where target = 2 

對於工作實例檢查Here

+0

可能應該是UNION ALL,而不是UNION –

+0

聯合可以,因爲我只想要一個結果不是全部。 –

3

您可以:

http://www.postgresql.org/docs/7.4/static/functions-conditional.html

像這樣的聲明應該做你想要什麼,雖然我沒有PostgreSQL的周圍與測試:

SELECT CASE 
     WHEN source = 2 THEN a, b 
     WHEN target = 2 THEN c, d 
     ELSE 0 
END 
+1

對我而言,Postgres支持'then'子句的'a,b'。你能否以這種方式提供違反標準的文件?我似乎無法複製它。 –

+0

這不起作用。它說在昏迷旁邊的第二行有一個錯誤。 –

4

我假設你有一個表稱爲'數據庫'(一個表格的可怕名稱),看起來像這樣:

a | b | c | d | source | target 
------+------+------+------+--------+-------- 
    11 | 22 | 33 | 44 |  1 |  2 
    111 | 222 | 333 | 444 |  2 |  2 
1111 | 2222 | 3333 | 4444 |  2 |  1 

然後,您可以查詢它是這樣的:

select 
    case when source=2 then a else null end as a, 
    case when source=2 then b else null end as b, 
    case when target=2 then c else null end as c, 
    case when target=2 then d else null end as d 
from database; 

,並得到這樣的結果:

a | b | c | d 
------+------+------+------ 
     |  | 33 | 44 
    111 | 222 | 333 | 444 
1111 | 2222 |  |  

根據需要,只有A和B都回來,在那裏源= 2,且c和c回來,在那裏目標= 2。

+0

。 。 +1,這是應該接受的答案。 –

+0

用於假設名爲「數據庫」的表格 –

1

如何:

select a,b,c,d from (select a,b from database where source=2 UNION select c,d from database where target=2)