即使缺少关系,也可以获得多对多关系中的所有记录

时间:2017-10-09 22:55:27

标签: mysql sql

我有一个user表,group表和user_group表,用于多对多。

我很困惑如何获得属于特定组的所有用户的列表,如果用户不属于当前组,我仍然希望他的记录列出,组字段设置为 NULL < /强>

3 个答案:

答案 0 :(得分:3)

如果我理解正确,你可以这样做:

select u.*, ug.group_id
from users u left join
     user_group ug
     on ug.user_id = u.user_id and ug.group_id = <the group>;

答案 1 :(得分:0)

如果您不关心包含没有用户的群组,这应该有效;应该在NULL group_id的userIDs下收集所有无组用户。

SELECT g.group_id, GROUP_CONCAT(u.user_id) AS userIDs
FROM `users` AS u
LEFT JOIN `user_group` AS ug ON u.user_id = ug.user_id
LEFT JOIN `group` AS g ON ug.group_id = g.group_id
GROUP BY g.group_id
;

答案 2 :(得分:0)

如果我得到了你想说的话,那就应该为你做好准备。

--Creating data for users
;with users as (
    select 1 as ID, 'Jonh' as name union all
    select 2 as ID, 'Suzan' as name union all
    select 3 as ID, 'Wolv' as name union all
    select 4 as ID, 'Rine' as name union all
    select 5 as ID, 'Someone' as name
)

Select  *
into    #users
From    users

--Creating data for groups
;with groups as (
    select 1 as ID, 'Admin' as descri union all
    select 2 as ID, 'Users' as descri union all
    select 3 as ID, 'NoOne' as descri
)

Select  *
into    #groups
From    groups

--Creating data for N x N relation
;with users_group as (
    select 1 as users, 1 as groups union all
    select 2 as users, 1 as groups union all
    select 1 as users, 2 as groups
)

Select  *
into    #users_group
From    users_group

--Declare @groupID int = null
Declare @groupID int = 1

select  #users.id
        , #users.name
        , #groups.descri
from    #groups

        Inner Join  #users_group as link
        on          link.groups = #groups.ID
        and         (#groups.id = @groupID or @groupID is null) --Filter here

        Full outer join #users --Full outer join to always bring users
        on          #users.Id = link.users


drop table #users_group
drop table #groups
drop table #users