从第二个表计数行

时间:2012-04-11 16:30:15

标签: php mysql count left-join

我在mysql数据库中有两个表

id|name
_______
1 |red
2 |blue
3 |green
4 |white

和用户

id|name  |group
_______________
1 |joe   |1
2 |max   |1
3 |anna  |2
4 |lisa  |2

所以...乔和马克斯在“红色”组中,安娜和丽莎都在“蓝色”组中。

如何制作包含数量的组的简单列表 该群体中的人 例如

red - 2
blue - 2
green - 0
white - 0

6 个答案:

答案 0 :(得分:1)

检查这是否有效....

SELECT COUNT(*), groups.name FROM groups, users WHERE users.group=groups.id GROUP BY groups.name

<强>更新

SELECT groups.name, COUNT(users.*) FROM groups LEFT JOIN users
ON groups.id=users.group GROUP BY groups.name

即使它们没有任何相关名称,也会保留颜色

答案 1 :(得分:1)

大多数其他答案基本上都是正确的,但忘记了一个重要的细节:GROUP是SQL中的保留字,因此您的列名必须进行转义:

SELECT groups.name, COUNT(*) AS total_members
FROM groups 
LEFT OUTER JOIN users 
ON users.`group` = groups.id
GROUP BY groups.id

答案 2 :(得分:0)

尝试一下:

select g.name, count(u.id) from groups g
left join users u on g.id = u.group
group by g.id, g.name

答案 3 :(得分:0)

试试这个

SELECT COUNT(g.id) as count, g.name 
FROM groups as g
LEFT JOIN users as u 
ON u.group = g.id
GROUP BY g.id

答案 4 :(得分:0)

这应该有效

SELECT g.*, COUNT(DISTINCT u.id) FROM `groups` g
INNER JOIN `users` u on g.id = u.group
GROUP BY u.id

答案 5 :(得分:0)

也许这应该有用

SELECT g.name, COUNT( u.id ) AS Totoal
FROM  `groups` g
INNER JOIN  `users` u ON g.id = u.group
GROUP BY g.id