我有一个包含以下结构的表
id | season
1 | 1
2 | 1
2 | 2
3 | 2
4 | 2
5 | 1
我希望查询返回总 ID的计数,例如:
total_season2 | new | existing
3 | 2 | 1
我可以使用多个查询或使用php来完成它,但我希望将结果放在一个查询中
答案 0 :(得分:0)
由于您不需要选择所有行,因此可以使用带有子查询的空选择来获取所需的数据。可能有更有效的方法来获取相同的数据,但这将有效:
SELECT
(SELECT COUNT(id) FROM seasons s WHERE s.season = 2) as total_season2,
(SELECT COUNT(id) FROM seasons s WHERE s.season = 2 AND (SELECT distinct COUNT(ss.id) FROM seasons ss WHERE ss.id = s.id) = 1) as new,
(SELECT COUNT(id) FROM seasons s WHERE s.season = 2 AND (SELECT distinct COUNT(ss.id) FROM seasons ss WHERE ss.id = s.id) > 1) as existing