[英]Mysql — 2 counts in one query, bad second count result
I just inherited a codebase, and there's an existing query that is incorrect. 我刚刚继承了一个代码库,并且现有的查询不正确。 It looks like (genericized tables & columns here):
它看起来像(这里的通用表和列):
select p.user_id, p.photo_id, p.date, count(p.photo_id) as 'Photos', count(v.photo_id) as 'Views'
from photos p
LEFT OUTER JOIN userviews v on v.user_id = p.user_id and v.photo_id = p.photo_id
where p.photo_id in ( 1,2,3 [...] )
GROUP BY photo_id, user_id
ORDER BY user_id, photo_id
The result set is close to correct, so close that no one noticed it was wrong for a while. 结果集接近正确,非常接近,没有人注意到它有一段时间是错误的。
If there's no data in table 2 (userviews), then the resulting row is correct. 如果表2(用户视图)中没有数据,则生成的行是正确的。
However, if there is data there, the resultset is duplicating the count values from table 1, ie: 但是,如果有数据,结果集将复制表1中的计数值,即:
1082 3381 2012-05-25 08:50:20 3 3 <--WRONG, should be 1
1082 3387 2012-07-26 15:02:36 2 2 <--WRONG, should be 4
1117 3381 2012-05-23 03:46:02 1 0 <--CORRECT
1117 3382 2012-05-23 03:45:54 1 0 <--CORRECT
1117 3383 2012-05-23 03:45:09 1 0 <--CORRECT
Now, if this were SQL server, I'd just rewrite the damn thing using a CTE, but Mysql doesn't support a WITH clause, and I don't think I can subquery these as they return multiple values. 现在,如果这是SQL服务器,我只是使用CTE重写该死的东西,但是Mysql不支持WITH子句,我不认为我可以查询这些因为它们返回多个值。
So how do I fix this in Mysql? 那么如何在Mysql中解决这个问题呢? Thanks in advance, I'm stumped on this one.
在此先感谢,我对此感到难过。
Try this query 试试这个查询
SELECT p.user_id, p.photo_id, p.Photos, ph.date, v.Views
FROM photos ph,
(SELECT p.user_id, p.photo_id, count(p.photo_id) as 'Photos'
FROM photos p
WHERE p.photo_id in ( 1,2,3 [...] )
GROUP BY p.photo_id, p.user_id ) p,
(SELECT v.user_id, v.photo_id, count(v.photo_id) as 'Views'
FROM userviews v
WHERE v.photo_id in ( 1,2,3 [...] )
GROUP BY v.photo_id, v.user_id
) v
WHERE p.user_id = v.user_id AND
p.photo_id = v.photo_id AND
ph.photo_id = p.photo_id AND
ph.user_id = p.user_id
ORDER BY p.user_id, p.photo_id
EDIT Using left join 编辑使用左连接
SELECT p.user_id, p.photo_id, p.Photos, ph.date, v.Views
FROM (SELECT v.user_id, v.photo_id, count(v.photo_id) as 'Views'
FROM userviews v
WHERE v.photo_id in ( 1,2,3 [...] )
GROUP BY v.photo_id, v.user_id
) v left join (SELECT p.user_id, p.photo_id, count(p.photo_id) as 'Photos'
FROM photos p
WHERE p.photo_id in ( 1,2,3 [...] )
GROUP BY p.photo_id, p.user_id ) p
ON p.user_id = v.user_id AND p.photo_id = v.photo_id
left join photos ph
On ph.photo_id = p.photo_id AND
ph.user_id = p.user_id
ORDER BY p.user_id, p.photo_id
When you do not GROUP BY or aggregate all the items in the SELECT list, MySQL chooses the values for the other columns and you might get unexpected results. 当您没有GROUP BY或聚合SELECT列表中的所有项时,MySQL会选择其他列的值,您可能会得到意外的结果。 ( REFER ) that was the reason you were getting wrong results
( REFER )这就是你得到错误结果的原因
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.