根据 ID 匹配项来连接每一行中的所有值的 MySQL 语句


我们先创建一张表 -

mysql> create table DemoTable
(
   StudentId int,
   StudentFirstName varchar(100),
   StudentLastName varchar(100)
);
Query OK, 0 rows affected (0.54 sec)

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

mysql> insert into DemoTable values(1000,'Adam','Smith');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(1000,'John','Doe');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(1000,'David','Miller');
Query OK, 1 row affected (0.12 sec)

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

mysql> select *from DemoTable;

这将产生以下输出 -

+-----------+------------------+-----------------+
| StudentId | StudentFirstName | StudentLastName |
+-----------+------------------+-----------------+
|      1000 | Adam             | Smith           |
|      1000 | John             | Doe             |
|      1000 | David            | Miller          |
+-----------+------------------+-----------------+
3 rows in set (0.00 sec)

以下是根据 ID 匹配项连接每一行中的所有值的查询 -

mysql> select StudentId,group_concat(StudentFirstName),group_concat(StudentLastName) from DemoTable group by StudentId;

这将产生以下输出 -

+-----------+--------------------------------+-------------------------------+
| StudentId | group_concat(StudentFirstName) | group_concat(StudentLastName) |
+-----------+--------------------------------+-------------------------------+
|      1000 | Adam,John,David                | Smith,Doe,Miller              |
+-----------+--------------------------------+-------------------------------+
1 row in set (0.00 sec)

更新日期:2019 年 9 月 27 日

120 次浏览

开启你的事业

完成本课程获得认证

开始
广告