MySQL、Mariadb中GROUP_CONCAT 函数使用介绍
By:授客 QQ:1033553122
语法:
GROUP_CONCAT([DISTINCT] column_name [ORDER BY 序字段 ASC/DESC] [SEPARATOR '分隔符'])
注:测试时发现,排序似乎不起作用
实践
构造数据:
CREATE TABLE tb_test(
order_id INT,
goods_id INT,
user_name VARCHAR(7)
);
INSERT INTO tb_test VALUES(1000000001, 1, '授客'), (1000000001, 2, '授客'), (1000000001, 3, '授客'),(1000000002, 4, '小谢'), (1000000002, 5, '小谢'), (1000000002, 6, '小谢');
SELECT * FROM tb_test;
例子1:
查询每个用户购买的商品(按user_name分组,显示其购买的所有商品)
SELECT t1.`order_id` AS '订单号',
t1.`user_name` AS '用户名',
GROUP_CONCAT((CASE WHEN t1.`goods_id` = 1 THEN '小苹果' WHEN t1.`goods_id` = 2 THEN '雪梨' WHEN t1.`goods_id` = 3 THEN '香蕉' WHEN t1.`goods_id` = 4 THEN '小李子' WHEN t1.`goods_id` = 5 THEN '芭乐' WHEN t1.`goods_id` = 6 THEN '葡萄' END)) AS '商品'
FROM tb_test t1
GROUP BY t1.`user_name`;
结果:
例子2:
查询每个用户购买的商品(按user_name分组,显示其购买的所有商品),商品之间用";"分隔
SELECT t1.`order_id` AS '订单号',
t1.`user_name` AS '用户名',
GROUP_CONCAT((CASE WHEN t1.`goods_id` = 1 THEN '小苹果' WHEN t1.`goods_id` = 2 THEN '雪梨' WHEN t1.`goods_id` = 3 THEN '香蕉' WHEN t1.`goods_id` = 4 THEN '小李子' WHEN t1.`goods_id` = 5 THEN '芭乐' WHEN t1.`goods_id` = 6 THEN '葡萄' END) SEPARATOR ';') AS '商品'
FROM tb_test t1
GROUP BY t1.`user_name`;
结果:
例子3:
查询每个用户购买的商品(按user_name分组,显示其购买的所有商品),商品名称不重复
SELECT t1.`order_id` AS '订单号',
t1.`user_name` AS '用户名',
GROUP_CONCAT((CASE WHEN t1.`goods_id` = 1 THEN '小苹果' WHEN t1.`goods_id` = 2 THEN '雪梨'
WHEN t1.`goods_id` = 3 THEN '香蕉' WHEN t1.`goods_id` = 4 THEN '小李子'
WHEN t1.`goods_id` = 5 THEN '芭乐' WHEN t1.`goods_id` = 6 THEN '葡萄' END) ) AS '商品'
FROM tb_test t1
GROUP BY t1.`user_name`;
运行结果:
修改脚本如下:
SELECT t1.`order_id` AS '订单号',
t1.`user_name` AS '用户名',
GROUP_CONCAT(DISTINCT (CASE WHEN t1.`goods_id` = 1 THEN '小苹果' WHEN t1.`goods_id` = 2 THEN '雪梨'
WHEN t1.`goods_id` = 3 THEN '香蕉' WHEN t1.`goods_id` = 4 THEN '小李子'
WHEN t1.`goods_id` = 5 THEN '芭乐' WHEN t1.`goods_id` = 6 THEN '葡萄' END) ) AS '商品'
FROM tb_test t1
GROUP BY t1.`user_name`;
运行结果如下: