按子查询(Mysql)生成的cloumn的值进行筛选
我有这样一个问题:按子查询(Mysql)生成的cloumn的值进行筛选,mysql,subquery,Mysql,Subquery,我有这样一个问题: select name,(select count(*) from relation r where s.id_student = r.id_student) courses from student s; +-----------+--------+ | name | student | +-----------+--------+ | Jorge | 4 | | Guillermo | 2 | | Hecto
select name,(select count(*) from relation r where s.id_student = r.id_student) courses
from student s;
+-----------+--------+
| name | student |
+-----------+--------+
| Jorge | 4 |
| Guillermo | 2 |
| Hector | 2 |
| Diana | 2 |
| Diego | 4 |
| Mariano | 2 |
| Fernanda | 1 |
| Ricardo | 2 |
| Issac | 2 |
| Jaime | 0 |
+-----------+--------+
10 rows in set (0.00 sec)
但我只想展示那些有两门以上课程的学生。如果我做了一个“where courses>2”会给我一个错误,因为该列不在表students中。那么,如何过滤以获得所需的结果呢
注意:我知道我可以使用联接而不是子查询来解决此问题,但如果没有为子查询解决方案找到aswer,我会发疯。您可以使用
HAVING
子句来筛选子查询提供的结果集
select name,
(select count(*) from relation r where s.id_student = r.id_student) courses
from student s
HAVING courses >2
;
哇,这么简单,我在试图解决这个问题时也很困惑,太多了。