[英]SQL join one to many relationship - count number of votes per image?
Okay, so I have 2 tables: 好的,所以我有2张桌子:
images votes
---------------------------- --------------------
image_id | name | square_id vote_id | image_id
---------------------------- --------------------
1 someImg 14 1 45
2 newImg 3 2 18
3 blandImg 76 3 1
... ...
n n
This is a one to many relationship. 这是一对多的关系。 Each image can have multiple votes, but a vote can only be related to one image.
每个图像可以有多个投票,但是一个投票只能与一个图像相关。 I'm trying to produce a join query which will show the image id, and the number of votes it has under a specified condition (say, based on
square_id
). 我正在尝试生成一个联接查询,该查询将显示图像ID及其在指定条件下的投票数(例如,基于
square_id
)。 Thus the query result would look similar to this: 因此,查询结果将类似于以下内容:
query_result
----------------------
image_id | vote_count
----------------------
18 46
26 32
20 18
...
55 1
But the best I can do is this: 但是我能做的最好的是:
query_result
----------------------
image_id | vote_id
----------------------
18 46
18 45
18 127
26 66
26 43
55 1
See the problem? 看到问题了吗? Each
image_id
is listed multiple times for each vote_id
it has. 每个
image_id
被多次列出每个vote_id
它。 This is the query which produces this: 这是产生此查询的查询:
SELECT images.image_id, votes.vote_id
FROM votes JOIN images ON images.image_id=votes.image_id
I just can't seem to create a vote_count
column which is the sum of all the votes that image has. 我似乎无法创建一个
vote_count
列,该列是该图像具有的所有投票的总和。 Is there some way that I can use the count()
function to do so, that I'm simply not aware of? 有什么方法可以使用
count()
函数这样做,而我根本不知道吗?
You need to GROUP BY images.image_id
and use COUNT(votes.vote_id)
: 您需要
GROUP BY images.image_id
并使用COUNT(votes.vote_id)
:
SELECT images.image_id, COUNT(votes.vote_id) AS cote_count
FROM votes
JOIN images ON images.image_id=votes.image_id
GROUP BY images.image_id
You generally need to use GROUP BY
when using aggregates like COUNT()
: 在使用类似
COUNT()
聚合时,通常需要使用GROUP BY
:
SELECT images.image_id, count(votes.vote_id) AS vote_count
FROM votes
JOIN images ON images.image_id=votes.image_id
GROUP BY images.image_id;
I'm not 100% clear on what you mean by 我不清楚您的意思是100%
and the number of votes it has under a specified condition (say, based on
square_id
)"?以及它在指定条件下(例如,基于
square_id
)的square_id
”?
Your model seems to model square_id
against image and can only be used as a where
filter on images
, not on a relationship between votes and images. 您的模型似乎是根据图像对
square_id
建模的,只能用作images
的where
过滤器,而不能用作投票和图像之间的关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.