SQL SUM and COUNT returning wrong values

一笑奈何 提交于 2021-02-08 11:47:19

问题


I found a bunch of similar questions but nothing worked for me, or I am too stupid to get how to do it right. The visit count works fine if I use COUNT(DISTINCT visits.id) but then the vote count goes totally wrong - it displays a value 3 to 4 times larger than it should be.

So this is the query

SELECT SUM(votes.rating), COUNT(visits.id)
FROM topics
LEFT JOIN visits ON ( visits.content_id = topics.id )
LEFT JOIN votes ON ( votes.content_id = topics.id )
WHERE topics.id='1'
GROUP BY topics.id

The votes table looks like this

id int(11) | rating tinyint(4) | content_id int(11) | uid int(11)

visits table

id int(11) | content_id int(11) | uid int(11)

topics table

id int(11) | name varchar(128) | message varchar(512) | uid int(11)

help?


回答1:


Basically, you're summing or counting the total number of rows potentially returned. So, if there are three visits and four votes for each id, then the visits will be multiplied by four and the votes by three.

I think what you want can easiest be ackomplished by using subqueries:

SELECT (SELECT SUM(v.rating) FROM votes v WHERE v.content_id = t.id), 
       (SELECT COUNT(vi.id) FROM visits vi WHERE vi.content_id = t.id)
FROM topics t
WHERE t.id=1 
GROUP BY t.id



回答2:


I suspect the problem is in the join with the table votes.
If votes have more than one row you will have the count using also that duplicated rows.
If you use distinct you skip the duplication of the Ids (due to the join with vote).
As a first tiral I will temporarely disapble the join with votes and see what happen.
Hope it helps




回答3:


Without seeing the data it is a bit tough to debug, but I would guess it is because there are more visits than votes. The following should work for you:

SELECT (SELECT SUM (rating) FROM votes WHERE votes.content_id = topics.id), (SELECT COUNT (1) FROM visits WHERE visits.content_id = topics.id) FROM topics WHERE topics.id = 1




回答4:


You need to do this as two separate subqueries:

SELECT sumrating, numvisit
FROM (select visits.content_id, count(*) as numvisits
      from visits
      ) tvisit left outer join
     (select votes.content_id, SUM(votes.rating) as sumrating 
      from votes
      group by votes.content_id
     ) v
     ON ( v.content_id = tvisit.content_id )
WHERE tvisit.content_id='1'

As it turns out, you don't need to join in the topic table at all.



来源:https://stackoverflow.com/questions/11545771/sql-sum-and-count-returning-wrong-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!