1

我需要选择一个有一个连接表的表

例如有表:

Role,AccountRole,Account
AccountRole - many to many relationship

需要选择角色,有一个账号

Role table
id  name 
1   admin 
2   user 
3   external 

Account table
id  name 
1   homer 
2   jessica 
3   simpson 

AccountRole table
account_id role_id 
1          1 
1          2 
2          2 
3          3 

询问:

SELECT  role.id    
FROM    Role role
        INNER JOIN AccountRole accRole
            ON accRole.role_id = role.id

        INNER JOIN Account acc
            ON accRole.account_id = acc.id

GROUP BY role.id
HAVING COUNT(*) = 1

在查询结果中:

role.id 
2 
3 

但我需要 role.id which role.name = "external"(在这种情况下 role.id = 3,但不是 2)

这该怎么做

4

1 回答 1

1
SELECT  a.ID    -- change this to the original name of your Role Column
FROM    Role a
        INNER JOIN AccountRole b
            ON a.RoleID = b.RoleID -- an assumption that their linking
                                   -- column name is RoleID
        INNER JOIN Account c
            ON b.AccountID = c.AccountID -- an assumption that their linking
                                         -- column name is AccountID
GROUP BY a.ID
HAVING COUNT(*) = 1
于 2012-12-12T15:47:20.037 回答