Mysql - 2在一个查询中计数,第二个计数结果错误

时间:2013-03-19 04:22:40

标签: mysql sql

我刚刚继承了一个代码库,并且现有的查询不正确。它看起来像(这里的通用表格和列):

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子句,我不认为我可以查询这些因为它们返回多个值。< / p>

那么如何在Mysql中解决这个问题呢?在此先感谢,我对此感到难过。

1 个答案:

答案 0 :(得分:1)

尝试此查询

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

使用左连接编辑

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

如果您没有GROUP BY或聚合SELECT列表中的所有项目,MySQL会选择其他列的值,您可能会得到意外的结果。 (REFER)这就是你得错结果的原因