2011-09-07 41 views
-1

使用Postgres。SQL:選擇關係數== 1的用戶

我有用戶,其中有項目。項目有一個「類型」列。我試圖讓用戶,有的項目,其項目類型不是空的列表,以及這些「非空」項目總數正好是1

所需的查詢:

select * 
from users 
join items 
where items.type IS NOT NULL 
and the count of (items.type IS NOT NULL) == 1 

如果有更多我可以提供的信息,請告訴我。

在此先感謝!

+1

你有一個笛卡爾乘積存在;您沒有指定用戶和項目表的加入方式。我知道這不是你的問題,但在你能回答你的問題之前,你需要告訴我們如何加入這兩個表 – Icarus

+0

你需要兩個表中的所有列嗎? – BlackTigerX

+0

一旦腦筋已經平息下來,也許你可以在你的問題上多加點...? –

回答

4
select users.id, count(items.type) 
from users 
join items on items.user_id = user.id 
where items.type IS NOT NULL 
group by users.id 
having count(items.type) = 1 
0

無論你的方言 - 你需要把你的兩張桌子聯繫起來。或者:

table a JOIN table b on some field(s) 

OR

WHERE some fields in table a = some field(s) in table b 

而且 - 考慮如何關聯的表 - 精確匹配,全部只有匹配B等