[英]Sql query to find the absence of a relationship between two tables
I am trying to write a query that finds the absence of a relationship between Table C and Table A. The only table that knows about this relationship is Table B. 我正在尝试编写一个查询,该查询查找表C和表A之间不存在关系。唯一知道这种关系的表是表B。
|Table A| |Table B| |Table C|
--------- --------- ---------
|id: 1 | |id: 2, a_id: 1, c_id: 3| |id: 3 |
|id: 4 | |id: 5 |
For every entry in Table C that is not associated with Table A, I want to know about it. 对于与表A不相关的表C中的每个条目,我想知道这一点。
Example output: 输出示例:
|Output|
--------
|c_id: 3, a_id: 4|
|c_id: 5, a_id: 1|
|c_id: 5, a_id: 4|
Hopefully you can follow that. 希望你能遵循。 I've been racking my mind on it and I am not seeing the solution.
我一直在考虑,但没有看到解决方案。
Do a cross-join between A
and C
, use the NOT EXISTS
clause to exclude the combinations found in B
. 在
A
和C
之间进行交叉连接,使用NOT EXISTS
子句排除B
找到的组合。
SELECT C.id AS c_id, A.id AS a_id
FROM C, A
WHERE NOT EXISTS ( SELECT * FROM B WHERE B.a_id = A.id AND B.c_id = C.id )
Since you tagged sql-server
, you can also use the EXCEPT
clause. 由于标记了
sql-server
,因此还可以使用EXCEPT
子句。
SELECT C.id AS c_id, A.id AS a_id FROM C, A
EXCEPT
SELECT c_id, a_id FROM B
The first one works on all SQL databases. 第一个适用于所有SQL数据库。 The second only works on some, eg
第二个仅适用于某些,例如
EXCEPT
works for MS SQL Server, PostgreSQL, DB2 and SQLite. EXCEPT
适用于MS SQL Server,PostgreSQL,DB2和SQLite。 MINUS
works for Oracle. MINUS
为Oracle工作。 try this 尝试这个
SELECT C.id AS c_id, A.id AS a_id
FROM C cross join A left outer join b on B.a_id = A.id AND B.c_id = C.id
WHERE b.id is null
try Left join with find the null value 尝试左连接查找空值
select A.id, C.id
from B left outer join A on A.id= B.a_id left outer join C on C.id = B.c_id
where B.a_id is null or B.c_id is null
This should do it for you. 这应该为您做。
SELECT c.id, a.id
FROM c
JOIN a
WHERE (SELECT id
FROM b
WHERE b.a_id = a.id AND
b.c_id = c.id) IS NULL
ORDER BY c.id, a.id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.