CREATE TABLE student (
sid INT (4) PRIMARY KEY,
sname VARCHAR (36),
course VARCHAR (36),
score INT,
grade INT (4)
) ENGINE = INNODB DEFAULT CHARSET = utf8;
INSERT INTO student VALUES (1,'aa','语文',60,1);
INSERT INTO student VALUES (2,'aa','数学',70,1);
INSERT INTO student VALUES (3,'aa','英语',80,1);
INSERT INTO student VALUES (4,'bb','语文',70,1);
INSERT INTO student VALUES (5,'bb','数学',60,1);
INSERT INTO student VALUES (6,'bb','英语',60,1);
INSERT INTO student VALUES (7,'cc','语文',90,2);
INSERT INTO student VALUES (8,'cc','数学',50,2);
INSERT INTO student VALUES (9,'cc','英语',60,2);
INSERT INTO student VALUES (10,'dd','语文',70,2);
INSERT INTO student VALUES (11,'dd','数学',60,2);
INSERT INTO student VALUES (12,'dd','英语',90,2);
功能:根据条件表达式对分组后的内容进行过滤,因此使用having时通常都会先使用group by。
-- 查询平均分大于68分的人
SELECT sname,AVG(score) FROM student GROUP BY sname HAVING AVG(score)>68;
相同:
两者都是对数据过滤,只保留有效的数据。
不同:
WHERE是对原始的记录过滤,HAVING是对分组后的记录过滤,WHERE必须写在HAVING前面,顺序不可颠倒,否则报错。