1 CREATE DATABASE mahaiwuji; 2 3 USE mahaiwuji; 4 5 CREATE TABLE student ( 6 sid INT (4) PRIMARY KEY, 7 sname VARCHAR (36), 8 course VARCHAR (36), 9 score INT, 10 grade INT (4) 11 ) ENGINE = INNODB DEFAULT CHARSET = utf8; 12 13 INSERT INTO student VALUES (1,'aa','语文',60,1); 14 INSERT INTO student VALUES (2,'aa','数学',70,1); 15 INSERT INTO student VALUES (3,'aa ' , ' English ' , 80 , 1 ); 16 17 INSERT INTO student VALUES ( 4 , ' bb ' , ' Chinese ' , 70 , 1 ); 18 INSERT INTO student VALUES ( 5 , ' bb ' , ' Mathematics ' , 60 , 1 ); 19 INSERT INTOstudent VALUES ( 6 , ' bb ' , ' English ' , 60 , 1 ); 20 21 INSERT INTO student VALUES ( 7 , ' cc ' , ' Chinese ' , 90 , 2 ); 22 INSERT INTO student VALUES ( 8 , ' cc ' , ' Math ' , 50 ,2); 23 INSERT INTO student VALUES (9,'cc','英语',60,2); 24 25 INSERT INTO student VALUES (10,'dd','语文',70,2); 26 INSERT INTO student VALUES (11,'dd',' Mathematics ' , 60 , 2 ); 27 INSERT INTO student VALUES ( 12 , ' dd ' , ' English ' , 90 , 2 );
2. Example demonstration
Function: Filter the grouped content according to conditional expressions , so when using having, group by is usually used first.
1 - Query the average score of more than 68 points 2 SELECT sname, AVG (score) FROM student GROUP BY sname HAVING AVG (score) > 68 ;
3. Similarities and differences between HAVING and WHERE
the same
Both filter data and only retain valid data.
different
WHERE is to filter the original records, HAVING is to filter the records after grouping; WHERE must be written in front of HAVING, the order cannot be reversed or the operation will be wrong.