简体   繁体   中英

MySQL: SELECT and COUNT in same query

I have these two tables:

CITY TABLE

在此输入图像描述

CLUB TABLE

在此输入图像描述

What I'm trying to do, is to select with the same query all cities that contain published clubs ( published field set to 1) and the total of clubs published in that city.

At the moment, I am doing it with two steps, but I would like to improve performance by merging these in just one query.

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

After this, I'm doing a query for each city just to get the COUNT.

Something like this:-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM