mysql中合并字符并用逗号隔开,mysql包含查询

mysql中合并字符并用逗号隔开
记得和GROUP BY 一同使用
在这里插入图片描述
代码:普通合并

GROUP_CONCAT(name) AS nameList

代码:指定分隔符合并

GROUP_CONCAT(name SEPARATOR ',')

代码:去重并指定分隔符合并

GROUP_CONCAT(DISTINCT name SEPARATOR ',')

mysql包含查询

FIND_IN_SET('内容',salesmanids)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用MySQL内置函数`replace`和`substring_index`来将逗号隔开字符串转为多行,具体做法如下: 假设我们有一个表`t`,其有一个字段`str`存储了逗号隔开字符串: ``` mysql> select * from t; +----+--------------+ | id | str | +----+--------------+ | 1 | a,b,c | | 2 | d,e,f,g,h,i | +----+--------------+ ``` 我们想将这个逗号隔开字符串转为多行,可以使用如下SQL语句: ``` mysql> select id, replace(substring_index(str, ',', n), ' ', '') as str from t join (select 1 as n union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7) nums on char_length(str) - char_length(replace(str, ',', '')) >= n - 1; ``` 解释一下上面的SQL语句: - `substring_index(str, ',', n)`:取出逗号隔开字符串第n个逗号前的子串; - `replace(..., ' ', '')`:去除取出的子串的空格; - `join (select 1 as n union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7) nums`:使用一个子查询`nums`生成一个包含数字1~7的临时表,用于将逗号隔开字符串转为最多7行; - `char_length(str) - char_length(replace(str, ',', ''))`:计算逗号隔开字符串逗号的个数; - `>= n - 1`:将第n个逗号前的子串转为一行时,需要保证逗号的个数不少于n-1个。 执行上面的SQL语句后,可以得到如下结果: ``` +----+------+ | id | str | +----+------+ | 1 | a | | 1 | b | | 1 | c | | 2 | d | | 2 | e | | 2 | f | | 2 | g | | 2 | h | | 2 | i | +----+------+ ``` 其,每个逗号隔开的子串已经被转为了多行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值