简体   繁体   English

MySQL左连接不返回所有行

[英]MySQL left join doesn't return all rows

I have two tables: "images" and "images_votes". 我有两张桌子:“images”和“images_votes”。 It's for a rating system, so I need to count both the votes and the sum of the scores 这是一个评级系统,所以我需要计算投票和分数的总和

When I make a LEFT JOIN, not all the rows from "images" appear, only those that have votes, and one more. 当我进行LEFT JOIN时,不会出现“images”中的所有行,只有那些有投票的行,还有一个。

Here's the query: 这是查询:

SELECT `images`.`id` AS id, COUNT( images_votes.id_image ) AS votes, SUM( images_votes.val ) AS val
FROM (
`images`
)
LEFT JOIN `images_votes` ON `images`.`id` = `images_votes`.`id_image`
GROUP BY `images_votes`.`id_image`

And here's the complete example: 这是完整的例子:

http://www.sqlfiddle.com/#!2/05526/1 http://www.sqlfiddle.com/#!2/05526/1

I have 5 images, so I'd expect that the result would return 5 rows. 我有5张图片,所以我希望结果会返回5行。 I only get 3: 2 that have votes, and one more. 我只得到3:2的投票,还有一个。

Why does this happen? 为什么会这样?

How can I get the 5 (all) rows? 如何获得5(所有)行?

Change the group by 改变group by

GROUP BY `images`.`id`

You want to group by the table that contains all images. 您希望按包含所有图像的表进行分组。

SQLFiddle demo SQLFiddle演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM