我有两个表应该是一对多的关系,但是在表的许多方面似乎存在一些阻止创建关系的记录。违反参照完整性。
由于两个表中都有很多记录,有没有办法查询哪些记录在多方面,而不是在一方?
**Ex.**
Table 1: (one side)
(pk)AccountId
Table 2: (many side)
(pk)UserId
(fk)AccountId <-- Some accountId's are not in Table 1
答案 0 :(得分:9)
select *
from table2 t2
where not exists(
select 1
from table1 t1
where t1.AccountId = t2.AccountId
)
答案 1 :(得分:4)
select a.*
from Table2 as a
where not exists (select null from table1 as b where b.AccountId = a.AccountId);
答案 2 :(得分:2)
SELECT table2.UserId, table2.AccountId
FROM table1 RIGHT JOIN table2 ON table1.AccountId = table2.AccountId
WHERE table1.AccountId IS NULL;
答案 3 :(得分:1)
FROM Table2 t2
WHERE t2.AccountId not in (SELECT t1.AccountId FROM Table1 t1)
或者如果您更喜欢加入......
FROM Table2 t2
LEFT JOIN Table1 t1
ON t2.AccountId = t1.AccountId
WHERE t1.AccountId is null