• MySQL学习笔记:一道group by+group_concat解决的小问题


      闲来无事,逛逛V2EX发现一道MySQL数据库题目,原题如下:

      遂打开很长一段时间都没用过SQLyog,噗呲噗呲的干起活来……

      建测试表:

    CREATE TABLE test_001
    (
      id INT,
      type2 VARCHAR(10),
      bizId VARCHAR(10),
      batchId INT
    )
    
    INSERT INTO test_001(id,type2,bizId,batchId) VALUES(1,1,'uid1',1);
    INSERT INTO test_001(id,type2,bizId,batchId) VALUES(2,1,'uid2',1);
    INSERT INTO test_001(id,type2,bizId,batchId) VALUES(3,2,'fid1',1);
    INSERT INTO test_001(id,type2,bizId,batchId) VALUES(4,2,'fid2',1);
    INSERT INTO test_001(id,type2,bizId,batchId) VALUES(5,1,'uid3',2);
    INSERT INTO test_001(id,type2,bizId,batchId) VALUES(6,2,'fid3',3);
    
    SELECT * FROM test_001;

      第一次解决,KO!

    SELECT batchId,
           GROUP_CONCAT(uid) AS uid,
           GROUP_CONCAT(typeid) AS typeid
    FROM
        (SELECT batchId,
               CASE WHEN type2 = '1' THEN bizId
               ELSE NULL END AS uid,
               CASE WHEN type2 = '2' THEN bizId
               ELSE NULL END AS typeid
        FROM test_001) g
    GROUP BY batchId;

      看起来没什么毛病,哈哈哈!继续看看其他高手有没有什么值得学习的解决方案。

    SELECT * FROM test_001;
    SELECT batchId,
           GROUP_CONCAT(CASE WHEN type2 = 1 THEN bizId ELSE NULL END) AS "uid",
           GROUP_CONCAT(CASE WHEN type2 = 2 THEN bizId ELSE NULL END) AS "typeid"
    FROM test_001
    GROUP BY batchId;

      不采用子查询显得更加的优雅,get!结果符合要求!

      附原文链接:https://www.v2ex.com/t/535679


       顺手温习一下concat、concat_ws、group_concat函数的使用方法。

    •   concat(str1,str2,str3,...) 字符串拼接

      如果有任何一个参数为null,则返回值为null。

    •   concat_ws(separator,str1,str2,...)

      指定分隔符拼接,分隔符不能为null。

    •   group_concat( ) 分组拼接

      group_concat([distinct] col [order by xxx desc] [separator '分隔符'])

    SELECT * FROM test_001
    
    -- 例子1
    SELECT batchId,
           GROUP_CONCAT(bizId ORDER BY bizId DESC SEPARATOR '_') AS xxx
    FROM test_001
    GROUP BY batchId
    
    -- 例子2
    SELECT batchId,
           GROUP_CONCAT(CONCAT_WS('-',type2,bizId) ORDER BY bizId)
    FROM test_001
    GROUP BY batchId

    END 2019-03-26 15:27:36

  • 相关阅读:
    chrome中打开 swf下载的问题
    爱对人比爱上人更重要
    ActiveMQ集群
    ActiveMQ相关API
    ActiveMQ持久化
    ActiveMQ处理模式
    ActiveMQ
    JMS与消息队列
    微服务设计、拆分原则
    web常用服务架构
  • 原文地址:https://www.cnblogs.com/hider/p/10600182.html
Copyright © 2020-2023  润新知