2017-02-23 39 views
0

如何計算event_participants表中參與者的數量,並顯示結果爲零的event_title。這是我的表在左側加入查詢中顯示0個結果

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

你怎麼確定你正在得到一個正確的結果?你使用PHP?如果是的話,告訴我們你的PHP代碼..! –

回答

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 

應該工作

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 
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