MySQL多对多的完整组合可能性

时间:2014-08-21 23:16:44

标签: mysql

当GroupMembership表中没有条目时,我想要的是Users.id和Groups.id与GroupMembership.id的每种可能组合。当有...时不为空。

例如,说有3个组,3个用户。用户1在组1中,用户2在组1和组中。 2,用户3没有组,组3没有用户。我正在寻找一个看起来有点像这样的列表:

--> user1
U.id = 1
G.id = 1
Gm.id = 1

U.id = 1
G.id = 2
Gm.id = (null - I.e there isn't an entry in the table that intersects this U.id & G.id combo)

U.id = 1
G.id = 3
Gm.id = (null - I.e there isn't an entry in the table that intersects this U.id & G.id combo)

--> user2
U.id = 2
G.id = 1
Gm.id = 2

U.id = 2
G.id = 2
Gm.id = 3

U.id = 2
G.id = 3
Gm.id = (null - I.e there isn't an entry in the table that intersects this U.id & G.id combo)

--> user3
U.id = 3
G.id = 1
Gm.id = (null - I.e there isn't an entry in the table that intersects this U.id & G.id combo)

U.id = 3
G.id = 2
Gm.id = (null - I.e there isn't an entry in the table that intersects this U.id & G.id combo)

U.id = 3
G.id = 3
Gm.id = (null - I.e there isn't an entry in the table that intersects this U.id & G.id combo)

我可以获得所有这些用户和可能的gms:

SELECT t1.id, t2.idGroupMembership FROM auth.users t1 LEFT JOIN AcmeCo.GroupMembership t2 ON t1.id = t2.idUser WHERE t1.staff = 1 ORDER BY id, idGroup

但是,如果我试图将群组滑入等式......:

SELECT t1.email, t2.idGroupMembership, t3.idGroup FROM auth.users t1 LEFT JOIN AcmeCo.GroupMembership t2 ON t1.id = t2.idUser LEFT JOIN AcmeCo.Groups t3 ON t3.idGroup = t2.idGroup WHERE t1.staff = 1

...我没有收到全套小组 - 它没有显示不相交的记录。希望这是有道理的。

由于

2 个答案:

答案 0 :(得分:1)

您可以使用CROSS JOIN。这对我使用sqlite和你的测试数据很有用。

    SELECT U.id, G.id, Gm.id
    FROM Users U CROSS JOIN Groups G
    LEFT JOIN GroupMembership Gm
    ON U.id = Gm.idUser AND G.id = Gm.idGroup;

结果:

    1|1|1
    1|2|
    1|3|
    2|1|2
    2|2|3
    2|3|
    3|1|
    3|2|
    3|3|

答案 1 :(得分:0)

要获得两个表之间的所有可能组合,您不应该LEFT JOIN它们。这个查询可以解决这个问题:

SELECT t1.email, t2.idGroup
  FROM auth.users AS t1, AcmeCo.Groups t2

现在,要选择组成员身份ID,请执行以下操作:

SELECT t1.email, t2.idGroup,
       (SELECT idGroupMembership FROM AcmeCo.GroupMembership WHERE idUser=t1.id AND idGroup=t2.idGroup) AS idGroupMembership
  FROM auth.users AS t1, AcmeCo.Groups t2
  ORDER BY t1.id, t2.idGroup
相关问题