2012-09-19 47 views
0

鑑於此查詢:Mysql在JOIN表語句中統計行數,這有可能嗎?

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行,這是已經主持一次,而不是在越來越不給予用戶ID匹配(9這個例子)。

dvd_moderators會是這個樣子:

id dogTag moderator 
219 2   9 
2226 2   7 

當然的主持人ID將爲其他條目改變。

使用COUNT作品大多當用戶ID主持人匹配除:

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)。

我怎麼能做到這一點?

謝謝。

回答

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到後如果有人有興趣。

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; 
+0

對不起,這不起作用,並給我完全相同的審覈計數作爲我上面的查詢上面:( – kakubei