2011-09-07 77 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等