如何计算event_participants表中的参与者数量,并显示event_title,结果为零。这是我的表
event_title
id | name
1 | New York
2 | Canada
event_participants
id | event_title_id | name
1 | 1 | Jon
2 | 1 | Mike
这是我的查询
SELECT count( * ) AS count
FROM event_participants AS t1
LEFT JOIN event_title AS t2 ON t1.event_title_id = t2.id
GROUP BY t1.event_title_id
我得到了正确的结果,但没有显示0结果。 我应该得到这样的结果
New York | 2
Canada | 0
答案 0 :(得分:1)
代替*
使用t2.id
它将起作用
SELECT count(t2.id) AS count
FROM event_participants AS t1
LEFT JOIN event_title AS t2 ON t1.event_title_id = t2.id
GROUP BY t1.event_title_id
答案 1 :(得分:0)
你的小组是问题所在。
您正在按event_title_id
分组,其中您没有ID 2
。
你应该做的是第一个表的name
组。
SELECT count( * ) AS count
FROM event_participants AS t1
LEFT JOIN event_title AS t2 ON t1.event_title_id = t2.id
GROUP BY t2.name
应该有效
答案 2 :(得分:0)
如下所示更改您的查询以获得所需的输出:
SELECT count(t2.id) AS count
FROM event_title AS t1
LEFT JOIN event_participants AS t2 ON t2.event_title_id = t1.id
GROUP BY t1.id
//To retrieve title also
SELECT t1.title,count(t2.id) AS count
FROM event_title AS t1
LEFT JOIN event_participants AS t2 ON t2.event_title_id = t1.id
GROUP BY t1.id