2

我有这两张表:

城市表

在此处输入图像描述

俱乐部桌

在此处输入图像描述

我要做的是使用相同的查询选择包含已发布俱乐部(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。

4

1 回答 1

4

像这样的东西: -

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
于 2012-11-22T11:34:51.307 回答