我有多对多的帐户< - > 用户关系。我正在尝试提取我和其他用户共享的所有帐户。到目前为止,我有一些我从this回答:
修改的内容SELECT *
FROM user
JOIN account_user ON account_user.user_id = user.id
JOIN account ON account.id = account_user.account_id
WHERE user.id IN ({my_id},{other_user_id})
GROUP BY account.id
HAVING COUNT(DISTINCT user.id) = 2
这似乎是在正确的轨道上,但account_user
表有一个'角色'字段,我想确保我得到的记录包含其他用户的角色,而不是我的。我如何调整这个以实现这一目标?
答案 0 :(得分:1)
在我的示例中,'user2'是另一个用户,'user1'是你:
-- query should work in most RDBMS
SELECT A1.account,
AU1.role AS user_2_account_role,
U1.uname AS user_2_name
FROM @account AS A1
JOIN @account_users AS AU1 ON AU1.account_id = A1.id
JOIN @user AS U1 ON U1.id = AU1.user_id
WHERE EXISTS(
-- get accounts that are 'mine'
SELECT *
FROM @user AS U2
JOIN @account_users AS AU2 ON AU2.user_id = U2.id
WHERE U2.uname = 'user1' -- 'mine'
AND AU2.account_id = AU1.account_id
)
AND U1.uname = 'user2' -- other user
我在SQL Server中准备的示例数据:
-- sample data in SQL SERVER
DECLARE @user TABLE(uname VARCHAR(20), id INT);
INSERT INTO @user(uname, id)
VALUES('user1', 1),
('user2', 2),
('user3', 3),
('user4', 4);
DECLARE @account TABLE(account VARCHAR(20), id INT);
INSERT INTO @account(account, id)
VALUES('account1', 1),
('account2', 2),
('account3', 3),
('account4', 4);
DECLARE @account_users TABLE(account_id INT, user_id INT, role VARCHAR(10));
INSERT INTO @account_users(account_id, user_id, role)
VALUES(1, 1, 'user1_role'),
(1, 2, 'user2_role'),
(2, 1, 'user1_role'),
(3, 3, 'user3_role'),
(3, 4, 'user4_role');
答案 1 :(得分:1)
这在我的Oracle下工作,同样的基本思想应该在任何DBMS下工作:
SELECT account.*, role
FROM account
JOIN account_user ON account_id = account.id AND user_id = :other_user_id
WHERE
account.id IN (SELECT account_id FROM account_user WHERE user_id = :my_id)
用简单的英语:
account
和account_user
。如果需要,您可以轻松加入user
(如您的SQL所示,但不是您的问题)。