HAVING 与 MySQL 数据库的 GROUP BY
要在 MySQL 数据库中同时使用 HAVING 和 GROUPBY,需要按照以下语法进行编写。此处,我们在 HAVING 下设置一个条件来检查最大值条件 −
SELECT yourColumnName FROM yourTableName GROUP BY yourColumnName HAVING MAX(yourColumnName) < yourValue;
让我们通过在 MySQL 数据库中创建一个表来查看一个示例 −
mysql> create table WhereAfterGroupDemo -> ( -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> UserProcess int, -> UserThreadId int -> ); Query OK, 0 rows affected (5.74 sec)
示例
使用 insert 命令在表中插入一些记录。查询如下 −
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)
使用 select 语句显示表中的所有记录。查询如下 −
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 来获取进程低于 1510 的 UserThreadId 的查询 −
mysql> SELECT UserThreadId FROM WhereAfterGroupDemo GROUP BY UserThreadId HAVING MAX(UserProcess) < 1510;
输出
+--------------+ | UserThreadId | +--------------+ | 3 | +--------------+ 1 row in set (0.00 sec)
广告