我的数据库中有两个表
队
id game_id name image
26 48 t t.png
27 48 t2 t2.png
得分
id team_id score
1 26 5
2 26 14
我的查询
SELECT t.id,t.name,t.image,sum(s.score)
FROM `team` AS t
LEFT JOIN score s ON (s.team_id=t.id) where t.game_id=48
我的查询总是给一个团队26团队
但它会像
id name image score
26 t t.png 19
27 t2 t2.png null
我无法理解我的查询中有什么问题。
答案 0 :(得分:1)
添加GROUP BY子句。试试这个查询。
SELECT t.id, t.name, t.image, sum(s.score) as total_score
FROM `team` AS t
LEFT JOIN `score` s ON (s.team_id = t.id)
WHERE t.game_id=48
GROUP BY t.id, t.name, t.image
答案 1 :(得分:1)
SELECT t.id,t.name,t.image,sum(s.score)
FROM `team` AS t
LEFT JOIN score s
ON (s.team_id=t.id)
where t.game_id=48
group by t.id
只需在其中添加group by
子句
答案 2 :(得分:1)
您已经汇总了分数,因此您的查询将会将两个团队的分数组合在一起,如果您想在两个单独的结果上返回它们。你必须把GROUP BY t.id
SELECT t.id,t.name,t.image,sum(s.score) FROM `team` AS t
LEFT JOIN score s ON (s.team_id=t.id)
where t.game_id=48 GROUP BY t.id
答案 3 :(得分:0)
分组将解决您的问题:
SELECT t.id,t.name,t.image,sum(s.score)
FROM `team` AS t
LEFT JOIN score s ON (s.team_id=t.id and t.game_id=48)
GROUP BY t.id