1

我得到了以下表格:

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

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

我想从一个查询中获得一个结果,该查询将为我提供每个图片 id、图片的视图以及votes特定 pic_id 表中的总票数

例子:

图片.id、图片.浏览量、总票数

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

4 回答 4

2

你需要有GROUP BY子句。

使用LEFT JOIN将显示 table 上的所有记录pictures,无论是否匹配 table 上的记录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
于 2013-11-09T19:13:49.683 回答
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`
于 2013-11-09T19:14:05.380 回答
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`;
于 2013-11-09T19:14:38.037 回答
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`
于 2013-11-09T19:14:48.897 回答