MySQL: SELECT and COUNT in same query

China☆狼群 提交于 2019-12-11 05:04:33

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/13511664/mysql-select-and-count-in-same-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!