我有这两个表:
CITY TABLE
CLUB TABLE
我要做的是,使用相同的查询选择包含已发布的俱乐部(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。
答案 0 :(得分:3)
这样的事情: -
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