在使用mysql数据库做一些业务时,比如将一条记录对应的多条详情数据记录归并为该条记录的某一个字段时,可以使用mysql的concat_ws和group_concat方法来进行处理:
使用concat_ws方法将详情数据的一条记录的多个字段先拼接合并为一个字段,然后使用group_concat将多条详情数据合并处理的字段拼接合并为一个字段。示例如下:
SELECT GROUP_CONCAT(tmp.fileInfo) AS fileInfos FROM ( SELECT CONCAT_WS( '-', file_name, file_url ) AS fileInfo FROM clientlogdetail WHERE serial_no = 11 ) tmp;
以上sql是使用CONCAT_WS方法将clientlogdetail表中的file_name和file_url字段通过分割符-拼接合并为一个字段,之后使用GROUP_CONCAT方法将前面拼接的结果继续拼接合并为一个字段。效果如下:
详情记录字段值:
详情记录字段合并结果:
所有详情记录结果合并结果:
group_concat还可以设置拼接前缀和后缀符,如group_concat("", 字段名,"'")是以单引号将结果组合进行拼接。