首页 数据库 mysql

mysql having 子句


HAVING 子句用来筛选分组后的各组数据。


一、HAVING 子句语法

SELECT 列名, 聚合函数(列名) FROM 表名 WHERE 条件表达式 GROUP BY 列表 HAVING 聚合函数(列名) operator value;


二、数据库实例


数据库有如下 score 表:



数据库还有如下 student 表:




一)不加 WHERE 子句

统计总成绩大于 200分的学生记录:


SELECT student_id,sum(score.score) as total_score FROM score INNER JOIN student ON score.student_id=student.ID GROUP BY student_id HAVING sum(score.score)> 200;

执行以上 SQL 语句,可得到如下结果集:




二)加 WHERE 子句

统计总成绩大于 200分、并且国籍是中国的学生记录:


SELECT student_id,sum(score.score) as total_score FROM score INNER JOIN student ON score.student_id=student.ID WHERE score.country = 'CN'

执行以上 SQL 语句,可得到如下结果集:





相关推荐