我想知道一个班有多少学生。如果有记录,以上工作正常。
但是,如果没有结果,则返回一个“记录”,其中包含所有字段 NULL
除了 students_count
返回零
+---+------+------+----------------+----------------+
| | id | name | professor_name | students_count |
+---+------+------+----------------+----------------+
| 1 | null | null | null | 0 |
+---+------+------+----------------+----------------+
我希望没有记录被退回。
如果一个记录返回,它看起来是这样的。
+---+----+-------------+----------------+----------------+
| | id | name | professor_name | students_count |
+---+----+-------------+----------------+----------------+
| 1 | 1 | Science 101 | Atkins | 16 |
+---+----+-------------+----------------+----------------+
我已经试过了 LEFT JOIN
以及 IFNULL(COUNT(DISTINCT students.id), null) AS students_count
但我好像没法让它发挥作用。
有什么帮助吗?
SELECT classes.*,
professors.name AS professor_name,
COUNT(DISTINCT students.id) AS students_count
FROM classes
INNER JOIN professors ON classes.professor_id = professors.id
LEFT JOIN students ON classes.id = students.class_id AND classes.class_id IS NOT NULL
WHERE classes.class_id = 3
使用下面的泛型数据,class\u id为3,结果应该是no records。但是 null
返回计数为0的记录。
+---+------+------+----------------+----------------+
| | id | name | professor_name | students_count |
+---+------+------+----------------+----------------+
| 1 | null | null | null | 0 |
+---+------+------+----------------+----------------+
使用类标识1将返回:
+---+----+-------------+----------------+----------------+
| | id | name | professor_name | students_count |
+---+----+-------------+----------------+----------------+
| 1 | 1 | Science 101 | Atkins | 4 |
+---+----+-------------+----------------+----------------+
通用数据
班级
+---+-------------+---------------+
| | name | professors_id |
+---+-------------+---------------+
| 1 | Science 101 | 1 |
+---+-------------+---------------+
| 2 | Math | 2 |
+---+-------------+---------------+
| 3 | English | 3 |
+---+-------------+---------------+
教授
+----+--------+
| id | name |
+----+--------+
| 1 | Atkins |
+----+--------+
| 2 | Button |
+----+--------+
| 3 | Castor |
+----+--------+
学生
+----+-------+------------+
| id | name | classes_id |
+----+-------+------------+
| 1 | Adam | 1 |
+----+-------+------------+
| 2 | Beth | 1 |
+----+-------+------------+
| 3 | Chris | 1 |
+----+-------+------------+
| 4 | David | 1 |
+----+-------+------------+
| 5 | Erma | 2 |
+----+-------+------------+
1条答案
按热度按时间r55awzrz1#
你可以试着用
INNER JOIN
而不是OUTER JOIN
,因为LEFT JOIN
将基于classes
table。sqlfiddle公司
编辑
HAVING
子句用于聚合函数条件。但你用HAVING classes.class_id IS NOT NULL
可以移动到where
```SELECT classes.*,
professors.name AS professor_name,
COUNT(DISTINCT students.id) AS students_count
FROM classes
INNER JOIN professors ON classes.professor_id = professors.id
LEFT JOIN students ON classes.id = students.class_id
WHERE classes.class_id = 3 AND classes.class_id IS NOT NULL