2013-08-28 189 views
0

這裏是我的簡單查詢:SQLite的查詢結合使用兩個結果集,

Select user_id, body 
from Messages where (Messages.author = 'john' and Messages.receipt = 'erick' 
UNION ALL (Messages.author = 'erick' and Messages.receipt = 'john'); 

我只是想給這兩個簡單的SELECT查詢相結合,得到的東西,如:

user_id body 
------------------ 
1  hello 
2  hi john 
2  hello this is erick 
1  this is john! 

我在做什麼錯?

回答

2

你可以試試:

Select user_id, body 
from Messages where (author = 'john' and receipt = 'erick') or 
(author = 'erick' and receipt = 'john') 

順便說一句,因爲你只從一個表中選擇數據,你不必每次你指的是現場時註明其名稱。

0

您可以通過更改WHERE條件做到這一點:

Select body 
from Messages 
    where 
(messages.author = 'john' and messages.receipt = 'erick') 
or 
(messages.author = 'erick' and messages.receipt = 'john') 
0

您應該使用以前的答案。我認爲他們表現更好。

我的回答是我只想澄清UNION關鍵字:UNION連接兩個行集,應使用如下:

-- One rowset: 
SELECT user_id, body FROM Messages WHERE author = 'john' AND receipt = 'erick' 
UNION ALL 
- Another rowset: 
SELECT user_id, body FROM Messages WHERE author = 'erick' AND receipt = 'john' 
; -- Union of both is returned! 

不過,如果你正在尋找一個表中的行避免UNION:剛剛寫了一個根據WHERE的條件。