将多个记录连接到一行?

时间:2014-03-18 08:49:18

标签: php mysql

这是我的数据库结构:

Users {User ID 1}
Roles {For example 2 roles: 1, 2}
User_roles {User ID 1: has Role 1, User ID 1: Has role 2}

如何使用join来获取这两个角色,因为此Query复制了用户:

SELECT * FROM `users` LEFT JOIN `user_roles` ON (`users`.`id` = `user_roles`.`user_id`)

我想输出一个看起来像这样的表:

User ID | Has Role 1 | Has Role 2
--------|------------|-----------
1       |    yes     |    yes

2 个答案:

答案 0 :(得分:3)

您可以按用户的ID进行分组。

SELECT 
    `users`.`id`, 
     IF(SUM(`roles`.`id` = 1), 'yes', 'no') AS `Has Role 1`,
     IF(SUM(`roles`.`id` = 2), 'yes', 'no') AS `Has Role 2`
FROM `users` 
LEFT JOIN `user_roles` ON `users`.`id` = `user_roles`.`user_id`
LEFT JOIN `roles` ON `roles`.role_id = `user_roles`.`role_id`
GROUP BY `users`.`id`

如果你只是使用角色的pk,那么你可以忽略LEFT JOIN roles

SELECT 
    `users`.`id`, 
     IF(SUM(`user_roles`.`role_id` = 1), 'yes', 'no') AS `Has Role 1`,
     IF(SUM(`user_roles`.`role_id` = 2), 'yes', 'no') AS `Has Role 2`
FROM `users` 
LEFT JOIN `user_roles` ON `users`.`id` = `user_roles`.`user_id`
GROUP BY `users`.`id`

答案 1 :(得分:2)

试试这个

SELECT
    usr.UserId,
    CASE WHEN role.HasRole1 = 1 THEN 'Yes' ELSE 'No' END AS HasRole1,
    CASE WHEN role.HasRole2 = 1 THEN 'Yes' ELSE 'No' END AS HasRole2
FROM users AS usr
LEFT JOIN user_roles AS role ON usr.id = role.user_id