Mariadb MySQL、Mariadb中GROUP_CONCAT函数使用介绍
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`;
运行结果如下:
作者:授客
微信/QQ:1033553122
全国软件测试QQ交流群:7156436
Git地址:https://gitee.com/ishouke
友情提示:限于时间仓促,文中可能存在错误,欢迎指正、评论!
作者五行缺钱,如果觉得文章对您有帮助,请扫描下边的二维码打赏作者,金额随意,您的支持将是我继续创作的源动力,打赏后如有任何疑问,请联系我!!!
微信打赏
支付宝打赏 全国软件测试交流QQ群