mysql - 按子查询生成的列的值过滤(Mysql)

标签 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 |
  | Hector    |      2 |
  | Diana     |      2 |
  | Diego     |      4 |
  | Mariano   |      2 |
  | Fernanda  |      1 |
  | Ricardo   |      2 |
  | Issac     |      2 |
  | Jaime     |      0 |
  +-----------+--------+
  10 rows in set (0.00 sec)

但我只想显示那些拥有超过 2 门类(class)的学生。如果我创建“where courses > 2”会给我一个错误,因为该列不在学生表中。那么,如何过滤才能获得所需的结果?

注意:我知道我可以使用 JOINS 而不是子查询来解决这个问题,但是找不到子查询解决方案的答案让我发疯。

最佳答案

您可以使用HAVING 子句来过滤子查询提供的结果集

select name,
(select count(*) from relation r where s.id_student = r.id_student) courses
 from student s
HAVING courses >2
;

关于mysql - 按子查询生成的列的值过滤(Mysql),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22848612/

相关文章:

asp.net - 无法检测到 CheckBox 的状态

MySQL/Percona : Date Range data integrity (via natural key)

sql - PostgreSQL 选择主记录并显示特定记录的详细信息列

mysql - 如何使用子查询作为存储过程的一部分 MySQL

mysql - "Subquery returns more than 1 row"错误

mysql - 如何使用 MySQL Workbench 在 EER 图中导入现有的表结构?

php - 使用PHP备份MySQL数据库,然后加密文件上传到另一台服务器

MySQL 多子查询

mysql - 优化 JOIN 子查询中的 WHERE 子查询

android - Sqlite 不同查询 From -To、To - From