MySQL数据库将多条记录的单个字段合并成一条记录

原SQL

SELECT acc.id,acc.acc_username,acc.acc_showname,T_PM_ROLE.role_name FROM  T_ACCOUNT acc,T_ACCOUNT_R_ROLE accRole ,T_PM_ROLE  WHERE acc.is_active =1 AND (accRole.is_active =1 AND  acc.id = accRole.acc_id) AND accRole.role_id = T_PM_ROLE.id
ORDER BY acc.id  

结果,有一个人有两个角色,如果想要将两个角色合并该如何呢?

答案:使用 group_concat函数

注:group_concat只有与group by语句同时使用才能产生效果

 

SELECT acc.id,acc.acc_username,acc.acc_showname,GROUP_CONCAT(T_PM_ROLE.role_name) FROM  T_ACCOUNT acc,T_ACCOUNT_R_ROLE accRole ,T_PM_ROLE  WHERE acc.is_active =1 AND (accRole.is_active =1 AND  acc.id = accRole.acc_id) AND accRole.role_id = T_PM_ROLE.id
 
GROUP BY acc_id
  
ORDER BY acc.id  

 

 

 

参考:http://www.cnblogs.com/wangtao_20/archive/2011/02/23/1961860.html

   https://www.2cto.com/database/201302/188404.html

 

posted @ 2017-10-22 18:06  Rainyn  阅读(42754)  评论(0编辑  收藏  举报