简体   繁体   中英

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.

|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.

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 .

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.

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. The second only works on some, eg

  • EXCEPT works for MS SQL Server, PostgreSQL, DB2 and SQLite.
  • MINUS works for Oracle.
  • MySQL doesn't have that feature.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM