根据 MySQL GROUP BY 按组列出所有行?


要按组列出所有行,可以使用 GROUP_CONCAT()。我们首先创建一个表 −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(20),
   Value varchar(100)
   );
Query OK, 0 rows affected (0.62 sec)

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

mysql> insert into DemoTable(Name,Value) values('John','John');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable(Name,Value) values('Carol','Carol');
Query OK, 1 row affected (0.21 sec)

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

mysql> insert into DemoTable(Name,Value) values('Carol','Works');
Query OK, 1 row affected (0.22 sec)

mysql> insert into DemoTable(Name,Value) values('John','At');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable(Name,Value) values('Carol','At');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable(Name,Value) values('John','Amazon');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable(Name,Value) values('Carol','Google');
Query OK, 1 row affected (0.16 sec)

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

mysql> select *from DemoTable;

这将产生以下输出 -

+----+-------+--------+
| Id | Name  | Value  |
+----+-------+--------+
| 1  | John  | John   |
| 2  | Carol | Carol  |
| 3  | John  | Works  |
| 4  | Carol | Works  |
| 5  | John  | At     |
| 6  | Carol | At     |
| 7  | John  | Amazon |
| 8  | Carol | Google |
+----+-------+--------+
8 rows in set (0.00 sec)

以下是按组列出所有行的查询。此处将获取“John”的值,即“John 在亚马逊工作,其 ID 为 1、3、5、7。它同样适用于“Carol” −

mysql> select Name, GROUP_CONCAT(Value SEPARATOR ' ') AS `Complete_Status` from DemoTable group by Name;

这将产生以下输出 −

+-------+-----------------------+
| Name  | Complete_Status       |
+-------+-----------------------+
| Carol | Carol Works At Google |
| John  | John Works At Amazon  | 
+-------+-----------------------+
2 rows in set (0.00 sec)

更新时间:30-Jul-2019

1 千以上次浏览

开启你的 职业生涯

通过完成本课程来获得认证

开始吧
广告