如何在单个 MySQL 查询中使用 GROUP BY 来按字段排序?

mysqlmysqli database

为此,我们首先创建一个表 −

mysql> create table DemoTable
(
   Message text
);
Query OK, 0 rows affected (1.15 sec)

使用 insert 命令在表中插入一些记录 −

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)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

这将产生以下输出 −

+---------+
| Message |
+---------+
| Good    |
| Bye     |
| Awesome |
| Bye     |
| Good    |
| Amazing |
| Awesome |
| Bye     |
+---------+
8 rows in set (0.00 sec)

以下是在单个 MySQL 查询中对 ORDER BY FIELD 和 GROUP BY 进行查询 −

mysql> select *from DemoTable
   group by Message
   order by field(Message,'Amazing','Awesome','Good','Bye');

这将产生以下输出 −

+---------+
| Message |
+---------+
| Amazing |
| Awesome |
| Good    |
| Bye     |
+---------+
4 rows in set (0.04 sec)

相关文章