来自另一个表的count()的SQL查询

时间:2013-11-09 19:11:08

标签: mysql sql

我收到了以下表格:

pictures
------------------------------------
id
name
views

votes
------------------------------------
id
user_id
pic_id

我想从一个查询中得到一个结果,该查询会给我每个图片ID,图片的视图,以及特定pic_id的表votes的总投票数

示例:

pictures.id,pictures.views,total votes

1 ------------ 78 ------------------ 123

2 ------------ 23 ------------------- 69

依旧......

我试过的代码:

SELECT `pictures`.`id`,`pictures`.`views`, COUNT(`votes`.`pic_id`) as votes
FROM `pictures` 
JOIN `votes`
ON `pictures`.`id` = `votes`.`pic_id`

但它并没有给我我想要的重复。

4 个答案:

答案 0 :(得分:2)

您需要GROUP BY条款。

使用LEFT JOIN将显示表pictures上的所有记录,无论是否有表votes上的匹配记录。

SELECT  a.id, a.name, a.views,
        COUNT(b.pic_id) TotalVotes
FROM    pictures a
        LEFT JOIN votes b
            ON a.id = b.pic_id
GROUP   BY a.id, a.name, a.views

答案 1 :(得分:1)

将左连接与组函数一起使用,普通连接关键字表示内连接,您需要左连接以实现一对多关系

SELECT `pictures`.`id`,`pictures`.`views`, COUNT(`votes`.`pic_id`) as votes
FROM `pictures` 
LEFT JOIN `votes`
ON `pictures`.`id` = `votes`.`pic_id`
GROUP BY `pictures`.`id`

答案 2 :(得分:1)

试试这个:

SELECT `pictures`.`id`,`pictures`.`views`, COUNT(`votes`.`pic_id`) as votes
FROM `pictures` 
JOIN `votes`
ON `pictures`.`id` = `votes`.`pic_id`
GROUP BY `votes`.`pic_id`;

答案 3 :(得分:1)

您需要使用GROUP BY子句尝试这样做:

SELECT `pictures`.`id`,`pictures`.`views`, COUNT(`votes`.`pic_id`) as votes
FROM `pictures` 
JOIN `votes`
ON `pictures`.`id` = `votes`.`pic_id`
group by `pictures`.`id`