How can I order in group but randomly with MySQL?


Let us first create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Value char(1)
   );
Query OK, 0 rows affected (0.66 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Value) values('X');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable(Value) values('Y');
Query OK, 1 row affected (0.09 sec)

mysql> insert into DemoTable(Value) values('X');
Query OK, 1 row affected (0.30 sec)

mysql> insert into DemoTable(Value) values('X');
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable(Value) values('Y');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable(Value) values('Z');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(Value) values('Z');
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-------+
| Id | Value |
+----+-------+
| 1  | X     |
| 2  | Y     |
| 3  | X     |
| 4  | X     |
| 5  | Y     |
| 6  | Z     |
| 7  | Z     |
+----+-------+
7 rows in set (0.00 sec)

Case 1 − Following is the query to group but randomly −

mysql> select DemoTable.*
   from DemoTable join
   (
   select Value, rand() as `random_Value`
   from DemoTable
   group by Value
   ) tbl2
   on DemoTable.Value = tbl2.Value
order by tbl2.`random_Value`;

This will produce the following output −

+----+-------+
| Id | Value |
+----+-------+
| 6  | Z     |
| 7  | Z     |
| 1  | X     |
| 3  | X     |
| 4  | X     |
| 2  | Y     |
| 5  | Y     |
+----+-------+
7 rows in set (0.00 sec)

Case 2 − Let us run the above query again to display since we are showing random records −

mysql> select DemoTable.*
   from DemoTable join
   (
   select Value, rand() as `random_Value`
   from DemoTable
   group by Value
   ) tbl2
   on DemoTable.Value = tbl2.Value
order by tbl2.`random_Value`;

This will produce the following output −

+----+-------+
| Id | Value |
+----+-------+
| 2  | Y     |
| 5  | Y     |
| 6  | Z     |
| 7  | Z     |
| 1  | X     |
| 3  | X     |
| 4  | X     |
+----+-------+
7 rows in set (0.00 sec)

Updated on: 30-Jul-2019

238 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements