- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
HAVING with GROUP BY in MySQL
To use HAVING with GROUPBY in MySQL, the following is the syntax. Here, we have set a condition under HAVING to get check for maximum value condition −
SELECT yourColumnName FROM yourTableName GROUP BY yourColumnName HAVING MAX(yourColumnName) < yourValue;
Let us see an example by creating a table in 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)
Example
Insert some records in the table using insert command. The query is as follows −
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)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from WhereAfterGroupDemo;
Output
+--------+-------------+--------------+ | UserId | UserProcess | UserThreadId | +--------+-------------+--------------+ | 1 | 1211 | 3 | | 2 | 1412 | 3 | | 3 | 1510 | 4 | | 4 | 1511 | 4 | +--------+-------------+--------------+ 4 rows in set (0.00 sec)
The following is the query to use HAVING and GROUP BY and get the UserThreaId with process less than 1510 −
mysql> SELECT UserThreadId FROM WhereAfterGroupDemo GROUP BY UserThreadId HAVING MAX(UserProcess) < 1510;
Output
+--------------+ | UserThreadId | +--------------+ | 3 | +--------------+ 1 row in set (0.00 sec)
Advertisements