我需要选择一个有一个连接表的表
例如有表格:
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,其中role.name =“external”(在这个例子中,role.id = 3,但不是2)
如何做到这一点
答案 0 :(得分: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