MySQL 查询根据公共匹配 ID 连接每行中的所有值
mysqlmysqli database更新于 2025/12/24 5:00:17
首先我们创建一个表 −
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)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

