2012-07-19 130 views
0

我有以下查詢工作就像我想要它,除了我想返回一個僞(?)列計數的單位數每個屬性有內部匹配連接。其中p.team = u.team和u.deleted ='0000-00-00 00:00:00'和u.rates!='0'。我可以在相同的查詢中做到這一點嗎?MySQL - 計數內部聯接查詢

屬性有幾個單位。他們都附屬於「團隊」(認爲用戶名)。

SELECT DISTINCT p.title, p.state, p.city, p.regionID, p.team, p.type, p.lat, p.lng, p.url_title 
     FROM Properties AS p 
     INNER JOIN Units AS u ON p.team = u.team 
     INNER JOIN Rates AS r ON p.team = r.team 
     INNER JOIN Photos AS ph ON p.team = ph.team 
     AND p.public = '1' 
     AND u.rates != '0' 
     AND p.deleted = '0000-00-00 00:00:00' 
     AND u.deleted = '000-00-00 00:00:00' 
     AND r.deleted = '000-00-00 00:00:00' 
     AND ph.deleted = '000-00-00 00:00:00' 
     GROUP BY p.id 
     ORDER BY p.created ASC 

回答

0

既然你只有一個聚合,你似乎被Properties行進行分組,這應該是比較容易的。你的意思是這樣的(未經測試)?

SELECT p.title, p.state, p.city, p.regionID, p.team, p.type, p.lat, p.lng, 
     p.url_title , COUNT(u.*) AS number_of_units 
FROM Properties AS p 
INNER JOIN Units AS u ON p.team = u.team 
INNER JOIN Rates AS r ON p.team = r.team 
INNER JOIN Photos AS ph ON p.team = ph.team 
AND p.public = '1' 
AND u.rates != '0' 
AND p.deleted = '0000-00-00 00:00:00' 
AND u.deleted = '000-00-00 00:00:00' 
AND r.deleted = '000-00-00 00:00:00' 
AND ph.deleted = '000-00-00 00:00:00' 
GROUP BY p.id, p.title, p.state, p.city, p.regionID, p.team, p.type, p.lat, p.lng, p.url_title 
ORDER BY p.created ASC 

根據您的意思,您可能需要改爲COUNT(DISTINCT(u.id))。你的問題很難說清楚。


作爲參考,「硬道路」是創建一個子查詢加入反對做計數。您可能需要這樣做來計算多個不相關的項目,或者按一件事物分組並計數:

SELECT DISTINCT p.title, p.state, p.city, p.regionID, p.team, p.type, p.lat, p.lng, 
       p.url_title, uuCount.number_of_units 
FROM Properties AS p 
INNER JOIN Units AS u ON p.team = u.team 
INNER JOIN Rates AS r ON p.team = r.team 
INNER JOIN Photos AS ph ON p.team = ph.team 
AND p.public = '1' 
AND u.rates != '0' 
AND p.deleted = '0000-00-00 00:00:00' 
AND u.deleted = '000-00-00 00:00:00' 
AND r.deleted = '000-00-00 00:00:00' 
AND ph.deleted = '000-00-00 00:00:00' 
INNER JOIN 
(
    SELECT uu.team, COUNT(*) AS number_of_units 
    FROM Units uu 
    WHERE uu.deleted = '0000-00-00 00:00:00' 
    AND u.rates != '0' 
    GROUP BY uu.team 
) AS uuCount ON p.team = uuCount.team 
GROUP BY p.id 
ORDER BY p.created ASC 
+0

COUNT(DISTINCT(u.id))訣竅。謝謝! – David 2012-07-19 18:25:39