这似乎是一个相当普遍的问题,虽然我还没有找到解决方案。
我有三张桌子, matchup,matchup_options,matchup_votes在创建时,会创建一个匹配项,创建“n”matchup_options并且matchup_votes为空,直到添加投票为止。
我的查询只返回一个值,即使我有两个matchup_options,NEITHER在matchup_votes表中有任何内容。 (这些应该返回0直到实际输入,这将开始正确计数)
SELECT matchup.matchupID, matchup_option.player_id, player.name, player.abr, count(matchup_vote.player_id) votes FROM matchup
INNER JOIN matchup_option ON matchup_option.matchupID= matchup.matchupID
INNER JOIN player ON player.player_id = matchup_option.player_id
LEFT JOIN matchup_vote ON matchup_vote.player_id = matchup_option.player_id
GROUP BY matchup_vote.player_id;
回归:
matchupID player_id name abr votes
111 249 Name SF 0
预期回报:
matchupID player_id name abr votes
111 249 Name SF 0
111 331 Name2 JS 0
谢谢!
答案 0 :(得分:2)
您的group by
子句不正确。您按matchup_vote.player_id
进行分组。我无法看到您的源数据,但这意味着只有一位玩家投了票。
您的查询应如下所示:
SELECT
matchup.matchupID
, matchup_option.player_id
, player.name
, player.abr
, count(matchup_vote.player_id) votes
FROM
matchup
INNER JOIN matchup_option
ON matchup_option.matchupID = matchup.matchupID
INNER JOIN player
ON player.player_id = matchup_option.player_id
LEFT JOIN matchup_vote
ON matchup_vote.player_id = matchup_option.player_id
GROUP BY
matchup.matchupID
, matchup_option.player_id
, player.name
, player.abr
答案 1 :(得分:1)
您正在进行GROUP BY matchup_vote.player_id;
每个player_id你会获得一行。