JOIN显示行,即使它为null

时间:2017-05-18 12:19:30

标签: mysql sql join

这是我的代码:

SELECT *, cr.club_winner AS 'club_winner', COUNT(club_winner) AS 'count_cw'
FROM clubs c
JOIN club_results cr 
WHERE c.club_id = cr.club_winner AND c.club_group = '1'
GROUP BY cr.club_winner
ORDER BY count_cw DESC, club_name

我在一个表中有俱乐部名称的行,在第二个表中有club_winner id。在表格中,我想展示现场排名,如果俱乐部从未成为赢家,则显示为“0”。不知道该怎么做。

现在它只显示至少一次获胜者的俱乐部。

我试图添加'case',但id不起作用

3 个答案:

答案 0 :(得分:2)

LEFT JOIN开始。我认为你想要的查询是这样的:

SELECT c.*, COUNT(cr.club_winner) AS count_wins
FROM clubs c LEFT JOIN
     club_results cr 
     ON c.club_id = cr.club_winner 
WHERE c.club_group = '1'
GROUP BY c.club_id
ORDER BY count_cw DESC, club_name;

答案 1 :(得分:0)

将您的where条款更改为on条款,并将您的加入更改为left join

SELECT *, cr.club_winner AS 'club_winner', COUNT(club_winner) AS 'count_cw'
FROM clubs c
LEFT JOIN club_results cr ON c.club_id = cr.club_winner AND c.club_group = '1'
GROUP BY cr.club_winner
ORDER BY count_cw DESC, club_name

答案 2 :(得分:0)

如果你没有第二张表中的值

,你应该使用左连接
SELECT *, cr.club_winner AS club_winner, COUNT(club_winner) AS count_cw
FROM clubs c
LEFT JOIN club_results cr on c.club_id = cr.club_winner AND c.club_group = '1'

GROUP BY cr.club_winner
ORDER BY count_cw DESC, club_name