我刚刚继承了一个代码库,并且存在一个不正确的现有查询。它看起来像(这里的通用表和列):
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
结果集接近于正确,如此接近以至于暂时没有人注意到它是错误的。
如果表 2(用户视图)中没有数据,则结果行是正确的。
但是,如果那里有数据,则结果集会复制表 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
现在,如果这是 SQL 服务器,我只会使用 CTE 重写该死的东西,但 Mysql 不支持 WITH 子句,而且我认为我不能对它们进行子查询,因为它们返回多个值。
那么如何在 Mysql 中解决这个问题呢?在此先感谢,我被这个难住了。