Sql server 使用联接仅显示没有匹配外键的记录
我整天都在做这件事,试着从多个网站上获得多个建议,但我似乎无法理解这一点 我使用的是MS SQL,我有3个SQL表,它们具有以下列:Sql server 使用联接仅显示没有匹配外键的记录,sql-server,Sql Server,我整天都在做这件事,试着从多个网站上获得多个建议,但我似乎无法理解这一点 我使用的是MS SQL,我有3个SQL表,它们具有以下列: USERS ------ UserID UserAccounts ------------ UserID AccountID Accounts -------- AccountID 下面是一个忽略数据类型的示例,仅供关系参考 我需要检索一个帐户列表,其中Users表中的给定UserID在UserAccounts表中没有条目 我遇到的问题是,许多用户可以与许多
USERS
------
UserID
UserAccounts
------------
UserID
AccountID
Accounts
--------
AccountID
下面是一个忽略数据类型的示例,仅供关系参考
我需要检索一个帐户列表,其中Users表中的给定UserID在UserAccounts表中没有条目
我遇到的问题是,许多用户可以与许多相同的帐户相关联。例如,在UserAccounts表中,此数据将是有效的:
UserAccounts
------------------
|UserID|AccountID|
------------------
| 1 | 1 |
| 2 | 1 |
| 2 | 3 |
因此,我不能使用IS NULL测试,并且使用@UserID无法使用给定用户名进行筛选,因为用户2与用户1不同,它仍然返回该行
这有什么意义吗?我简直不知所措
编辑:
我将查询更改为:
SELECT Accounts.ID, Accounts.CompanyAgencyName
FROM Accounts LEFT OUTER JOIN
(SELECT UserID, AccountID
FROM MyAccount.UserAccounts
WHERE (UserID = @UserID)) AS DerivedUserAccounts ON Accounts.ID = DerivedUserAccounts.AccountID
WHERE (DerivedUserAccounts.AccountID IS NULL)
ORDER BY Accounts.ID
其中738是给定的用户ID。或更一般的形式
create table #user (uid int primary key);
create table #account (aid int primary key);
create table #useraccount (uauid int,uaaid int PRIMARY KEY (uauid,uaaid));
insert into #user VALUES (1),(2),(3),(4);
insert into #account VALUES (1),(2),(3),(4);
insert into #useraccount VALUES (1,1),(2,1),(2,3);
SELECT * FROM #user WHERE NOT EXISTS (SELECT 1 FROM #useraccount WHERE uauid=uid)
看。我省略了从useraccount到account的第二个连接。完整的选择实际上应该是:
SELECT * FROM #user WHERE NOT EXISTS
(SELECT 1 FROM #useraccount JOIN #account ON aid=uaaid WHERE uauid=uid)
值为{1,2,3,4,5}的用户表 值为{10,20,30,40,50}的科目表 值为{1,20}、{1,50}、{2,20}、{3,10}、{4,40}、{4,50}的UserAccount表 查询:
declare @userId int; set @userId = 4;
with cte ( userId, accountId ) as
(
select userId, accountId from userAccount where userId = @userId
)
select a.*
from
account a
left join cte b on ( a.Id = b.accountId )
where
( b.accountId is null )
结果:
10,20,30为了在我的项目中工作,我不得不稍微修改一下查询,但这非常有效!选择Accounts.ID,Accounts.CompanyAgencyName从Accounts左侧外部连接选择UserID,MyAccount.UserAccounts中的AccountID,其中UserID=@UserID作为Accounts上的DerivedUserAccounts.ID=DerivedUserAccounts.AccountID,其中DerivedUserAccounts.AccountID按Accounts.ID排序为空。这可能有效,但出于性能原因,我试图避免使用notexists。我已经阅读了我在这方面所做的多次搜索,这些搜索可能会导致大型表中的性能问题。考虑到未来……我决定改用联接选项。@ZacharyWeber优化器会对这些问题进行排序-最后的执行计划将是相同的。查询对我所寻找的不起作用。如果表包含示例中使用的数据,@UserID参数为1,则输出结果应为{2,3,4},而不是{3,4},因为用户1在useraccount中没有id为2、3或4的帐户的记录。
declare @userId int; set @userId = 4;
with cte ( userId, accountId ) as
(
select userId, accountId from userAccount where userId = @userId
)
select a.*
from
account a
left join cte b on ( a.Id = b.accountId )
where
( b.accountId is null )