zoukankan      html  css  js  c++  java
  • MySQL的字符串连接函数CONCAT, CONCAT_WS,GROUP_CONTACT

     

    在搜索Mysql中怎么实现把一列的多行数据合并成一行时,找到了group_contact函数,它比SqlServer中的select @list=@list+列名 from 表名,的形式方便了许多,在此把字符串连接函数小小的总结一下。

    CONCAT(str1, str2,...): 返回结果为连接参数产生的字符串。如有任何一个参数为NULL ,则返回值为 NULL。 

    CONCAT_WS(separator,str1,str2,...): CONCAT With Separator ,是CONCAT()的特殊形式。 第一个参数是其它参数的分隔符。分隔符的位置放在要连接的两个字符串之间。分隔符可以是一个字符串,也可以是其它参数。如果分隔符为 NULL,则结果为 NULL。函数会忽略任何分隔符参数后的 NULL 值。 e.g: 

    mysql > SELECT CONCAT_WS(',','First Name',NULL,'Last Name');  -> First Name,Last Name 

    GROUP_CONCAT([DISTINCT] 要连接的字段 [Order BY ASC/DESC 排序字段] [Separator '分隔符']): 可以用来行转列。 e.g: 
    mysql> select * from tb;
     +------+------+ 
    | id | name | 
    +------+------+ 
    | 1 | 10 | 
    | 1 | 20 | 
    | 1 | 20 | 
    | 2 | 20 | 
    | 3 | 200 | 
    | 3 | 500 | 
    +------+------+ 

    myql> select id,group_concat(name) from tb group by id;

    +------+--------------------+ 
    | id | group_concat(name) | 
    +------+--------------------+ 
    | 1 | 10,20,20 | 
    | 2 | 20           | 
    | 3 | 200,500 | 
    +------+--------------------+ 

    mysql> select id,group_concat(name separator ';') from tb group by id;

    +------+----------------------------------+ 
    | id | group_concat(name separator ';') 
    | +------+----------------------------------+ 
    | 1 | 10;20;20 | 
    | 2 | 20         | 
    | 3 | 200;500 | 
    +------+----------------------------------+ 

    mysql> select id,group_concat(distinct name) from tb group by id;

    +------+-----------------------------+ 
    | id | group_concat(distinct name) | 
    +------+-----------------------------+ 
    | 1 | 10,20     | 
    | 2 | 20           | 
    | 3 | 200,500 | 
    +------+-----------------------------+

  • 相关阅读:
    用wamp配置的环境,想用CMD连接mysql怎么连
    Mysql删除表
    MySQL创建表
    Leetcode 130. Surrounded Regions
    Leetcode 111. Minimum Depth of Binary Tree
    Leetcode 110. Balanced Binary Tree
    Leetcode 98. Validate Binary Search Tree
    Leetcode 99. Recover Binary Search Tree
    Leetcode 108. Convert Sorted Array to Binary Search Tree
    Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
  • 原文地址:https://www.cnblogs.com/jamesbd/p/3932551.html
Copyright © 2011-2022 走看看