如何查找违反参照完整性的记录



我有两个表应该处于一对多关系中,但表的多端似乎有一些记录阻止了关系的创建。违反参照完整性。

由于两个表中都有很多记录,是否有办法查询哪些记录在多端,而不是在一侧?

**Ex.**
Table 1: (one side)
(pk)AccountId

Table 2: (many side)
(pk)UserId
(fk)AccountId  <--  Some accountId's are not in Table 1 
select *
from table2 t2
where not exists(
    select 1
    from table1 t1
    where t1.AccountId = t2.AccountId
)
select a.*
from Table2 as a
where not exists (select null from table1 as b where b.AccountId = a.AccountId);
SELECT table2.UserId, table2.AccountId
FROM table1 RIGHT JOIN table2 ON table1.AccountId = table2.AccountId
WHERE table1.AccountId IS NULL;

http://sqlfiddle.com/#!3/5b8e30/4

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

在 SQL SERVER 中,您可以使用以下命令:

 DBCC CHECKCONSTRAINTS WITH ALL_CONSTRAINTS

最新更新