zoukankan      html  css  js  c++  java
  • Mariadb MySQL、Mariadb中GROUP_CONCAT函数使用介绍

    MySQLMariadbGROUP_CONCAT 函数使用介绍

    By:授客 QQ1033553122

    语法:

    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`;

     

    运行结果:

    Mariadb <wbr>MySQL、Mariadb中GROUP_CONCAT函数使用介绍

     

    修改脚本如下:

    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`;

     

    运行结果如下:

    Mariadb <wbr>MySQL、Mariadb中GROUP_CONCAT函数使用介绍

     

  • 相关阅读:
    jQuery入门教程
    vue-lazyload 图片不更新
    Eggjs 设置跨域请求
    Vue.js错误: Maximum call stack size exceeded
    ubuntu nginx ssl 证书配置
    ubuntu 安装nginx, 出现 Unable to locate package
    nginx 判断移动端或者PC端 进入不同域名
    node.js 生成二维码
    Linux 配置ssh 免密码登录
    nodejs 从部署到域名访问
  • 原文地址:https://www.cnblogs.com/shouke/p/10157842.html
Copyright © 2011-2022 走看看