要在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 -> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1211,3); mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1412,3); mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1510,4); mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1511,4);
使用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的UserThreaId的查询-
mysql> SELECT UserThreadId FROM WhereAfterGroupDemo GROUP BY UserThreadId HAVING MAX(UserProcess) < 1510;
输出结果
+--------------+ | UserThreadId | +--------------+ | 3 | +--------------+ 1 row in set (0.00 sec)