我有一个名为“运动”的表,其中包含运动列表的列表,其他称为“季节”的表,其中包含特定运动的季节以及包含特定运动和季节的比赛的比赛。
我需要一个 MySQL 查询来打印体育项目列表,以及每个体育项目有多少个赛季和比赛。我的表格结构:
运动
+--------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(32) | NO | | NULL | |
| slug | varchar(45) | NO | | NULL | |
| description | varchar(128) | NO | | NULL | |
+--------------------+------------------+------+-----+---------+----------------+
季节
+--------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| id_sport | int(10) unsigned | NO | MUL | NULL | |
| name | varchar(32) | NO | | NULL | |
| slug | varchar(32) | NO | | NULL | |
+--------------------+------------------+------+-----+---------+----------------+
比赛
+--------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| id_season | int(10) unsigned | NO | MUL | NULL | |
| name | varchar(32) | NO | | NULL | |
| slug | varchar(64) | NO | | NULL | |
| description | varchar(128) | YES | | NULL | |
+--------------------+------------------+------+-----+---------+----------------+
我的查询结果需要包含:sports.*、total_seasons(季节的总和,其中seasons.id_sport=sports.id)和total_competitions(比赛的总和,其中competitions.id_season=seasons.id AND seasons.id_sport=sports .id)。
提前谢谢您!
最佳答案
使用左连接代替内连接
select
sports.id,
sports.name,
sports.slug,
sports.description,
ifnull(count( distinct seasons.id ), 0) as DistinctSeasons,
ifnull(count( distinct competitions.id ), 0) as TotalCompetitions
from
sports
left join seasons on sports.id=seasons.id_sport
left join competitions on seasons.id = competitions.id_season
group by
sports.id;
关于MySQL 查询其他表的 2 个 COUNT() 并带有 where 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4570745/