很难在标题中总结我的问题,所以它并没有完全覆盖......请注意:)
问题如下: 我有两个表,其中一个是用户表,第二个是包含用户/组组合的连接表。
我有用户可以订阅多个群组,我希望能够检查某人是否已经是某个群组的成员。我也希望能够获得用户信息,无论用户是否是相关组的成员。
所以我有:
表1:userID,userName等......
表2 :(具有唯一的复合索引)groupID,userID
我最好的尝试是:
SELECT * FROM table1 t1 LEFT JOIN table2 t2 ON t1.userID = t2.userID
WHERE userName = 'John' AND groupID = 1
(看John是否是第1组的成员)
我认为问题出在WHERE
子句中。该查询仅返回groupID = 1
成员的用户。但我想要的是如果John不是这个组的成员,则返回null。
任何想法,这甚至可能吗?谢谢! FAB
答案 0 :(得分:1)
您应该将WHERE
部分移至JOIN
SELECT *
FROM table1 t1
LEFT JOIN table2 t2
ON t1.userID = t2.userID
And userName = 'John'
AND groupID = 1
编辑我生成了自己的数据。试试这个
With Users as
(
Select 1 UserId, 'John' UserName
Union Select 2, 'Tom'
),
Groups as
(
Select 1 GroupId, 'Admin' GroupName
Union Select 2, 'Power Users'
Union Select 3, 'Users'
),
UserGroups as
(
Select 1 UserId, 1 GroupId
Union Select 2, 1
Union Select 2, 3
)
Select *
From Groups
Left Join (UserGroups
Inner Join Users
On Users.UserId = UserGroups.UserId
And UserName = 'John'
)
On Groups.GroupId = UserGroups.GroupId
结果:
GroupId GroupName UserId GroupId UserId UserName
----------- ----------- ----------- ----------- ----------- --------
1 Admin 1 1 1 John
2 Power Users NULL NULL NULL NULL
3 Users NULL NULL NULL NULL
答案 1 :(得分:1)
您需要将条件table2.groupID = 1
从WHERE
子句移至ON
条件(否则取消LEFT JOIN
):
SELECT u.*
, ug.groupID
FROM table1 AS u
LEFT JOIN table2 AS ug
ON ug.userID = u.userID
AND ug.groupID = 1
WHERE u.userName = 'John'
另一种选择是这种方法(类似于LEFT JOIN
):
SELECT *
, ( SELECT ug.groupID
FROM table2 AS ug
WHERE ug.userID = u.userID
AND ug.groupID = 1
) AS groupID
FROM table1 AS u
WHERE userName = 'John'
答案 2 :(得分:0)
你可能想这样做:
SELECT * FROM table1 t1 LEFT JOIN table2 t2 ON t1.userID = t2.userID
WHERE userName = 'John'
HAVING groupID = 1 OR groupID IS NULL
ORDER BY groupID DESC
LIMIT 1