3

我有两个应该是一对多关系的表,但是在表的许多方面似乎有一些记录阻止了创建关系。违反参照完整性。

由于两个表中都有很多记录,有没有一种方法可以查询到哪些记录在多方,但不是在一方?

**Ex.**

Table 1: (one side)
(pk)AccountId


Table 2: (many side)
(pk)UserId
(fk)AccountId  <--  Some accountId's are not in Table 1 
4

5 回答 5

10
select *
from table2 t2
where not exists(
    select 1
    from table1 t1
    where t1.AccountId = t2.AccountId
)
于 2012-06-06T19:52:02.227 回答
4
select a.*
from Table2 as a
where not exists (select null from table1 as b where b.AccountId = a.AccountId);
于 2012-06-06T19:52:38.740 回答
3
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

于 2012-06-06T19:52:30.873 回答
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
于 2012-06-06T19:54:57.530 回答
0

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

 DBCC CHECKCONSTRAINTS WITH ALL_CONSTRAINTS
于 2021-09-02T20:50:58.683 回答