GROUP_CONCAT是MySQL中的一个聚合函数,它用于将多行数据按照指定的顺序连接成一个字符串,并返回结果。下面是对GROUP_CONCAT函数的详解:
语法:
GROUP_CONCAT([DISTINCT] expr [,expr …]
[ORDER BY {unsigned_integer | col_name | expr}
[ASC | DESC] [,col_name …]]
[SEPARATOR str_val])
参数解释:
示例:
假设有一个表"orders",包含以下数据:
- +---------+------------+
- | order_id| product |
- +---------+------------+
- | 1 | Apple |
- | 1 | Orange |
- | 2 | Banana |
- | 3 | Apple |
- +---------+------------+
我们可以使用以下查询:
- SELECT order_id, GROUP_CONCAT(product ORDER BY product SEPARATOR ', ') AS products
- FROM orders
- GROUP BY order_id;
结果:
- +---------+-----------------------+
- | order_id| products |
- +---------+-----------------------+
- | 1 | Apple, Orange |
- | 2 | Banana |
- | 3 | Apple |
- +---------+-----------------------+
注意事项:
初始化SQL
- create table orders
- (
- order_id int null,
- product varchar(20) null
- );
-
- INSERT INTO test.orders (order_id, product) VALUES (1, 'Apple');
- INSERT INTO test.orders (order_id, product) VALUES (1, 'Orange');
- INSERT INTO test.orders (order_id, product) VALUES (2, 'Banana');
- INSERT INTO test.orders (order_id, product) VALUES (3, 'Apple');
执行SQL
- select *
- from orders;
-
- select order_id, GROUP_CONCAT(product)
- from orders
- GROUP BY order_id;
-
-
- SELECT order_id, GROUP_CONCAT(product ORDER BY product SEPARATOR ', ') AS products
- FROM orders
- GROUP BY order_id;


