Mysql 实现字段拼接的三个函数
给运营导出数据时,难免需要对字段进行拼接,如果Mysql可以完成的话,就可以少些很多代码。
- concat()
- concat_ws()
- group_concat()
Mysql确实有几个函数可以对字段进行拼接。
concat()
将多个字段使用空字符串拼接为一个字段
mysql>selectconcat(id,type)frommm_contentlimit10; +------------------+ |concat(id,type)| +------------------+ |100818image| |100824image| |100825video| |100826video| |100827video| |100828video| |100829video| |100830video| |100831video| |100832video| +------------------+ 10rowsinset(0.00sec)
不过如果有字段值为NULL,则结果为NULL。
mysql>selectconcat(id,type,tags)frommm_contentlimit10; +------------------------+ |concat(id,type,tags)| +------------------------+ |NULL| |NULL| |NULL| |NULL| |NULL| |NULL| |NULL| |NULL| |NULL| |NULL| +------------------------+ 10rowsinset(0.00sec)
concat_ws()
上面这种方式如果想要使用分隔符分割,就需要每个字段中间插一个字符串,非常麻烦。
concat_ws()可以一次性的解决分隔符的问题,并且不会因为某个值为NUll,而全部为NUll。
mysql>selectconcat_ws('',id,type,tags)frommm_contentlimit10; +--------------------------------+ |concat_ws('',id,type,tags)| +--------------------------------+ |100818image| |100824image| |100825video| |100826video| |100827video| |100828video| |100829video| |100830video| |100831video| |100832video| +--------------------------------+ 10rowsinset(0.00sec)
group_concat()
最后一个厉害了,正常情况下一个语句写成这样一定会报错的。
mysql>selectidfromtest_usergroupbyage; ERROR1055(42000):Expression#1ofSELECTlistisnotinGROUPBYclauseandcontainsnonaggregatedcolumn'test_user.id'whichisnotfunctionallydependentoncolumnsinGROUPBYclause;thisisincompatiblewithsql_mode=only_full_group_by
但是group_concat()可以将分组状态下的其他字段拼接成字符串查询出来
mysql>selectgroup_concat(name)fromtest_usergroupbyage; +--------------------+ |group_concat(name)| +--------------------+ |wen,ning| |wxnacy,win| +--------------------+ 2rowsinset(0.00sec)
默认使用逗号分隔,我们也可以指定分隔符
mysql>selectgroup_concat(nameseparator'')fromtest_usergroupbyage; +----------------------------------+ |group_concat(nameseparator'')| +----------------------------------+ |wenning| |wxnacywin| +----------------------------------+ 2rowsinset(0.00sec)
将字符串按照某个顺序排列
mysql>selectgroup_concat(nameorderbyiddescseparator'')fromtest_usergroupbyage; +---------------------------------------------------+ |group_concat(nameorderbyiddescseparator'')| +---------------------------------------------------+ |ningwen| |winwxnacy| +---------------------------------------------------+ 2rowsinset(0.00sec)
如果想要拼接多个字段,默认是用空字符串进行拼接的,我们可以利用concat_ws()方法嵌套一层
mysql>selectgroup_concat(concat_ws(',',id,name)separator'')fromtest_usergroupbyage; +------------------------------------------------------+ |group_concat(concat_ws(',',id,name)separator'')| +------------------------------------------------------+ |1,wen2,ning| |3,wxnacy4,win| +------------------------------------------------------+ 2rowsinset(0.00sec)
以上就是Mysql实现字段拼接的三个函数的详细内容,更多关于MySQL字符串拼接的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。