Mysql的两种“超过多少次”写法(力扣596)

题目:

有一个courses 表 ,有: student (学生) 和 class (课程)。

请列出所有超过或等于5名学生的课。

例如,表:

+---------+------------+
| student | class      |
+---------+------------+
| A       | Math       |
| B       | English    |
| C       | Math       |
| D       | Biology    |
| E       | Math       |
| F       | Computer   |
| G       | Math       |
| H       | Math       |
| I       | Math       |
+---------+------------+

应该输出:

+---------+
| class   |
+---------+
| Math    |
+---------+

Note:
学生在每个课中不应被重复计算。

 

答案1:

select a.class from
(select count(distinct student) as num, class from courses group by class) a
where a.num >= 5

答案2:
select class from courses group by class having count(class) > 4

对比一下效率是一样的:

[SQL] SELECT age from test_user GROUP BY age having count(age)>1;
受影响的行: 0
时间: 0.001s

[SQL]

select a.age from
(select count(age) as num, age from test_user group by age) a
where a.num >= 2;
受影响的行: 0
时间: 0.001s

 

posted @ 2019-04-09 15:32  昕友软件开发  阅读(370)  评论(0编辑  收藏  举报
欢迎访问我的开源项目:xyIM企业即时通讯