Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to ORDER BY FIELD with GROUP BY in a single MySQL query?
For this, let us first create a table −
mysql> create table DemoTable ( Message text ); Query OK, 0 rows affected (1.15 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Good');
Query OK, 1 row affected (0.43 sec)
mysql> insert into DemoTable values('Bye');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Awesome');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Bye');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('Good');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values('Amazing');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Awesome');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Bye');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------+ | Message | +---------+ | Good | | Bye | | Awesome | | Bye | | Good | | Amazing | | Awesome | | Bye | +---------+ 8 rows in set (0.00 sec)
Following is the query to ORDER BY FIELD with GROUP BY in a single MySQL query −
mysql> select *from DemoTable group by Message order by field(Message,'Amazing','Awesome','Good','Bye');
This will produce the following output −
+---------+ | Message | +---------+ | Amazing | | Awesome | | Good | | Bye | +---------+ 4 rows in set (0.04 sec)
Advertisements
