SQL select&从两张桌子算起

时间:2012-04-25 14:20:35

标签: sql sqlite

我有两张桌子,"用户" &安培; "项目"

用户表:

id username


1 sam

2彼得

3 andy

项目表:

id title uid


1 pr1 0

2 pr2 1

3 pr3 2

4 pr4 1

projects.uid表示将执行该作业的用户ID,0表示此项目尚未分配给任何用户。

我想要一个查询来根据用户计算和分组项目&返回这样的东西:

uid project_count


0 1

1 2

2 1

3 0

3 个答案:

答案 0 :(得分:2)

由于您没有返回username,因此您只需要projects表:

select u.id, count(*) as project_count
from users u
left outer join projects p on u.id = p.uid 
group by u.id
order by u.id

如果您也想要用户名,可以这样做:

select u.id, u.username, count(*) as project_count
from users u
left outer join projects p on u.id = p.uid
group by u.id, u.username
order by u.id

答案 1 :(得分:0)

select u.id, count(p.uid)
from users u
inner join project p 
on u.id = p.uid
group by p.uid

答案 2 :(得分:0)

非常感谢您的回答,但似乎没有一个回复正确的行,

这是我新发现的答案:

SELECT users.id,(SELECT COUNT(1) FROM projects WHERE projects.user_id = users.id) as 'count' FROM users ORDER BY id

我不太确定它的性能,但目前它的工作原理......