使用 MySQL 查询在一条记录中列出某个组中的所有项?


可以使用 GROUP_CONCAT() 函数在一行中列出某个组中的所有项。让我们首先创建一个表——

mysql> create table DemoTable
(
   ProductId int,
   ProductName varchar(40),
   ProductCategory varchar(40)
);
Query OK, 0 rows affected (0.67 sec)

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

mysql> insert into DemoTable values(100,'Product-1','1Product');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(101,'Product-2','2Product');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(100,'Product-1','3Product');
Query OK, 1 row affected (0.14 sec)

以下是使用 select 语句从表中显示所有记录的查询——

mysql> select *from DemoTable;

这将产生以下输出——

+-----------+-------------+-----------------+
| ProductId | ProductName | ProductCategory |
+-----------+-------------+-----------------+
| 100       | Product-1   | 1Product        |
| 101       | Product-2   | 2Product        |
| 100       | Product-1   | 3Product        |
+-----------+-------------+-----------------+
3 rows in set (0.00 sec)

以下是将某个组中的所有项列入单行的查询——

mysql> select ProductId,group_concat(ProductCategory) AS `GROUP` FROM DemoTable group by ProductId;

这将产生以下输出——

+-----------+-------------------+
| ProductId | GROUP             |
+-----------+-------------------+
| 100       | 1Product,3Product |
| 101       | 2Product          |
+-----------+-------------------+
2 rows in set (0.00 sec)

更新日期: 30-7-2019

1 千次浏览

启动您的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.