查找包含所有链接行的行

时间:2010-07-06 11:33:30

标签: mysql select

我有两张桌子:

User (id, name, etc)
UserRight (user_id, right_id)

我想找到拥有权限1,2和3的用户,但没有只有一个或两个用户的用户。此外,权限的数量会有所不同,因此(1,2,3)和(1,2,3,4,5,6,7)的搜索应该使用相同的查询。

本质:

SELECT *
FROM User
WHERE (
    SELECT right_id 
    FROM tblUserRight 
    WHERE user_id = id 
    ORDER BY user_id ASC
) = (1,2,3)

这在MySQL中是否可行?

3 个答案:

答案 0 :(得分:3)

SELECT u.id, u.name ...
FROM User u
JOIN UserRight r on u.id = r.user_id
WHERE right_id IN (1,2,3)
GROUP BY u.id, u.name ...
HAVING COUNT DISTINCT(right_id) = 3

答案 1 :(得分:0)

对应于我的答案中指出的错误,这里是一个带有count和子查询的解决方案:

SELECT *
FROM User
WHERE 3 = (
    SELECT Count(user_id)
    FROM tblUserRight 
    WHERE right_id IN (1,2,3)
    AND user_id = User.id
)

优化器当然可以将此更改为Martin Smith的解决方案(即使用分组)。

答案 2 :(得分:0)

您也可以使用PIVOT执行此操作,尤其是在您需要可视化表示的情况下。我在SQL Server上做了这个 - 你可以翻译它。

Declare @User Table (id  Int, name Varchar (10))
Declare @UserRight Table (user_id Int, right_id Int)

Insert Into @User Values (1, 'Adam')
Insert Into @User Values (2, 'Bono')
Insert Into @User Values (3, 'Cher')

Insert Into @UserRight Values (1, 1)
Insert Into @UserRight Values (1, 2)
Insert Into @UserRight Values (1, 3)
--Insert Into @UserRight Values (2, 1)
Insert Into @UserRight Values (2, 2)
Insert Into @UserRight Values (2, 3)
Insert Into @UserRight Values (3, 1)
Insert Into @UserRight Values (3, 2)
--Insert Into @UserRight Values (3, 3)


SELECT *
FROM @User U
    INNER JOIN @UserRight UR
        ON U.id = UR.User_Id
PIVOT
(
    SUM (User_Id)
    FOR Right_Id IN ([1], [2], [3])
) as xx
WHERE 1=1


SELECT *
FROM @User U
    INNER JOIN @UserRight UR
        ON U.id = UR.User_Id
PIVOT
(
    SUM (User_Id)
    FOR Right_Id IN ([1], [2], [3])
) as xx
WHERE 1=1
AND [1] IS NOT NULL
AND [2] IS NOT NULL
AND [3] IS NOT NULL