我有这样的查询:
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”中给我一个错误,因为该列不在表格中。那么,我如何过滤以获得所需的结果?
注意:我知道我可以使用JOINS而不是子查询来解决这个问题,但它让我发疯,不为子查询解决方案找到aswer。
答案 0 :(得分:1)
您可以使用HAVING
子句过滤子查询提供的结果集
select name,
(select count(*) from relation r where s.id_student = r.id_student) courses
from student s
HAVING courses >2
;