按 Id 分组并连接 MySQL 查询?


我们先创建一个表 -

mysql> create table DemoTable
(
   Id int,
   Name varchar(100)
);
Query OK, 0 rows affected (0.64 sec)

使用 insert 命令向表中插入一些记录 -

mysql> insert into DemoTable values(100,'Chris');
Query OK, 1 row affected (0.44 sec)
mysql> insert into DemoTable values(200,'Robert');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(100,'Chris');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(300,'David');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(400,'Mike');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(400,'Mike');
Query OK, 1 row affected (0.10 sec)

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

mysql> select *from DemoTable;

这将生成以下输出 -

+------+--------+
| Id   | Name   |
+------+--------+
|  100 | Chris  |
|  200 | Robert |
|  100 | Chris  |
|  300 | David  |
|  400 | Mike   |
|  400 | Mike   |
+------+--------+
6 rows in set (0.00 sec)

以下是将 MySQL group Concat 按 Id 分组的查询 -

mysql> select group_concat(Name)
from
(
   select distinct Id,Name from DemoTable
)
tbl;

这将生成以下输出 -

+-------------------------+
| group_concat(Name)      |
+-------------------------+
| Chris,Robert,David,Mike |
+-------------------------+
1 row in set (0.00 sec)

更新日期:26-9-2019

402 次浏览

开启您的 职业生涯

完成课程即可获得认证

入门
广告