Mysql计数JOIN表语句中的行,是否可能?

时间:2012-09-19 11:33:07

标签: mysql

鉴于此查询:

SELECT DISTINCT a.dogTag, a.dateEdited
FROM dvdpedia a
JOIN dvd_uploads b ON a.dogTag = b.dogTag
JOIN dvd_moderators c ON a.dogTag = c.dogTag
WHERE b.uploader != 9  AND c.moderator != 9
ORDER BY a.dogTag ASC
LIMIT 50;

我只想从dvd_moderators中选择仅出现一次的行,即仅被审核过一次而不是更多且与给定的userID不匹配的行(本例中为9)。

dvd_moderators看起来像这样:

id    dogTag    moderator
219    2         9
2226   2         7

当然,主持人ID会因其他条目而改变。

除非userID与主持人匹配,否则使用COUNT主要有效:

SELECT  a.dogTag, a.dateEdited, COUNT(c.dogTag) AS moderations
FROM dvdpedia a
JOIN dvd_uploads b ON a.dogTag = b.dogTag
JOIN dvd_moderators c ON a.dogTag = c.dogTag
WHERE b.uploader != 9 AND c.moderator != 9
GROUP BY c.dogTag
HAVING moderations = 1  
ORDER BY a.dogTag ASC
LIMIT 50;

然后它报告它只被审核一次(这是一个正确的查询,它丢弃与主持人= 9相匹配的行,因此计数结果为1而不是2)但是出于我需要的目的不正确。

基本上我想要只审核过一次的行,并且其中一个主持人与userID不匹配(上例中为9)。

我怎么能实现这个目标?

感谢。

2 个答案:

答案 0 :(得分:3)

感谢Guido在Sitepoint,这是他提供的解决方案。我把它放在这里,希望它能帮助处于类似情况的其他人:

SELECT a.dogTag, a.dateEdited
FROM dvdpedia a
JOIN dvd_uploads b ON a.dogTag = b.dogTag
JOIN dvd_moderators c ON a.dogTag = c.dogTag
JOIN
 (SELECT dogTag
  FROM dvd_moderators
  GROUP BY dogTag
  HAVING count(dogTag) = 1
 ) AS d
ON a.dogTag = d.dogTag
WHERE 1=1 
AND   b.uploader != 9 
AND   c.moderator != 9
ORDER BY a.dogTag ASC
LIMIT 50;

如果有人感兴趣的那个帖子的link

答案 1 :(得分:0)

SELECT  a.dogTag, a.dateEdited, COUNT(c.dogTag) AS moderations 
FROM dvdpedia a 
JOIN dvd_uploads b ON a.dogTag = b.dogTag AND b.uploader != 9
JOIN dvd_moderators c ON a.dogTag = c.dogTag AND c.moderator != 9
GROUP BY c.dogTag 
HAVING moderations = 1   
ORDER BY a.dogTag ASC 
LIMIT 50;