GROUP_CONCAT(expr)
该函数返回带有来自一个组的连接的非NULL值的字符串结果。其完整的语法如下所示:
GROUP_CONCAT([DISTINCT] expr [,expr ...]
[ORDER BY {unsigned_integer | col_name | expr}
[ASC | DESC] [,col_name ...]]
[SEPARATOR str_val])
在MySQL中,你可以获取表达式组合的连接值。
你可以使用DISTINCT删去重复值。
假若你希望多结果值进行排序,则应该使用 ORDER BY子句。
若要按相反顺序排列,将 DESC (递减) 关键词添加到你要用ORDER BY 子句进行排序的列名称中。
默认顺序为升序;可使用ASC将其明确指定。
SEPARATOR 后面跟随应该被插入结果的值中间的字符串值。默认为逗号 (‘,’)。通过指定SEPARATOR ” ,你可以删除所有分隔符。
===========================================
select u.id,u.user_name as userName, u.is_valid as isValid, GROUP_CONCAT(r.role_name SEPARATOR '-') AS roleName, GROUP_CONCAT(r.id) AS roleIdsStr FROM t_user u LEFT JOIN t_user_role ur ON u.id = ur.user_id LEFT JOIN t_role r ON ur.role_id = r.id WHERE u.is_valid = 1 GROUP BY id
缺少group by
select u.id,u.user_name as userName, u.is_valid as isValid, GROUP_CONCAT(r.role_name SEPARATOR '-') AS roleName, GROUP_CONCAT(r.id) AS roleIdsStr FROM t_user u LEFT JOIN t_user_role ur ON u.id = ur.user_id LEFT JOIN t_role r ON ur.role_id = r.id WHERE u.is_valid = 1
GROUP_CONCAT()中的内容全部集中到一条记录中,原来的记录也只显示了一条
select u.id,u.user_name as userName, u.is_valid as isValid, r.role_name AS roleName, r.id AS roleIdsStr FROM t_user u LEFT JOIN t_user_role ur ON u.id = ur.user_id LEFT JOIN t_role r ON ur.role_id = r.id WHERE u.is_valid = 1
select u.id,u.user_name as userName, u.is_valid as isValid, r.role_name AS roleName, r.id AS roleIdsStr FROM t_user u LEFT JOIN t_user_role ur ON u.id = ur.user_id LEFT JOIN t_role r ON ur.role_id = r.id WHERE u.is_valid = 1 GROUP BY id
GROUP_CONCAT()默认以 , 分隔
select u.id,u.user_name as userName, u.is_valid as isValid, GROUP_CONCAT(r.role_name ) AS roleName, GROUP_CONCAT(r.id) AS roleIdsStr FROM t_user u LEFT JOIN t_user_role ur ON u.id = ur.user_id LEFT JOIN t_role r ON ur.role_id = r.id WHERE u.is_valid = 1 GROUP BY id