当子查询返回null时删除外部查询上的行

时间:2013-07-16 05:25:22

标签: mysql

执行选择后,我收到错误"未知列'点'在' where子句'

如何从外部查询中删除包含从子查询返回的空记录的行? (我需要使用子查询,因为我需要运行另一组子查询来返回我之后的结果)

SELECT  
   s.student_name_first,
   s.student_name_last,
   (
   SELECT sum(i.points)
   FROM incidents i
   WHERE i.student = s.id
   ) AS points
FROM students s
WHERE points IS NOT NULL
GROUP BY s.id

我也尝试过,结果相同

SELECT  
   s.student_name_first,
   s.student_name_last,
   (
   SELECT sum(i.points) AS points
   FROM incidents i
   WHERE i.student = s.id AND points IS NOT NULL 
   ) AS p
FROM students s
GROUP BY s.id

提前致谢


解决方案:

我所寻找的是 HAVING

SELECT  
   s.student_name_first,
   s.student_name_last,
   (
   SELECT COALESCE(sum(i.incident_points),0)
   FROM incidents i
   WHERE i.student = s.id
   ) as points
FROM students s
GROUP BY s.id
HAVING points > 0

1 个答案:

答案 0 :(得分:2)

问题是您无法在SELECT子句中使用WHERE别名,它们必须位于HAVING

但是如果使用内连接,则首先不会获得任何空行。

SELECT s.student_name_first,
       s.student_name_last,
       SUM(i.points) AS points
FROM students s
JOIN incidents i
ON i.student = s.id
GROUP BY s.id