Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

การใช้ HAVING กับ GROUP BY ใน MySQL

ไวยากรณ์การใช้ HAVING กับ GROUP BY โดยตั้งเงื่อนไข MAX:

SELECT yourColumnName FROM yourTableName GROUP BY yourColumnName HAVING MAX(yourColumnName) < yourValue;

มาสร้างตาราง:

mysql> create table WhereAfterGroupDemo ( UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, UserProcess int, UserThreadId int ); Query OK, 0 rows affected (5.74 sec)

ตัวอย่าง

แทรกข้อมูล:

mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1211,3); Query OK, 1 row affected (0.10 sec) mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1412,3); Query OK, 1 row affected (0.39 sec) mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1510,4); Query OK, 1 row affected (0.19 sec) mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1511,4); Query OK, 1 row affected (0.31 sec)

แสดงข้อมูล:

mysql> select * from WhereAfterGroupDemo;

ผลลัพธ์

+--------+-------------+--------------+ | UserId | UserProcess | UserThreadId | +--------+-------------+--------------+ | 1 | 1211 | 3 | | 2 | 1412 | 3 | | 3 | 1510 | 4 | | 4 | 1511 | 4 | +--------+-------------+--------------+ 4 rows in set (0.00 sec)

คำสั่ง HAVING และ GROUP BY หา UserThreadId ที่ UserProcess สูงสุดน้อยกว่า 1510:

mysql> SELECT UserThreadId FROM WhereAfterGroupDemo GROUP BY UserThreadId HAVING MAX(UserProcess) < 1510;

ผลลัพธ์

+--------------+ | UserThreadId | +--------------+ | 3 | +--------------+ 1 row in set (0.00 sec)