2012-11-22 99 views
0

COUNT我有這兩個表:MySQL的:選擇並在同一查詢

City表

enter image description here

CLUB表

enter image description here

我」什麼m試圖做的是選擇相同的隊列ry包含已發佈俱樂部的所有城市(published字段設置爲1)以及該城市中發佈的俱樂部總數。

目前,我正在做兩個步驟,但我想通過在一個查詢中合併這些步驟來提高性能。

SELECT c.id, c.name, c.slug 
FROM city c, club cl 
WHERE c.id = cl.city_id 
AND (SELECT COUNT(*) 
     FROM club cl, city c 
     WHERE cl.city_id = c.id AND cl.published = 1) > 0 
GROUP BY c.id 

在此之後,我正在爲每個城市查詢以獲取COUNT。

回答

1

事情是這樣的: -

SELECT city.id, city.name, city.slug, COUNT(club.id) AS club_count 
FROM city 
INNER JOIN club 
ON city.id = club.city_id 
WHERE club.published = 1 
GROUP BY city.id, city.name, city.slug 
HAVING club_count > 0 
+0

這工作就像一個魅力。 HAVING子句中的錯字應該是'club_count'。 –

+0

Ooops,修正了錯字 – Kickstart