简体   繁体   中英

SQL query to extract data from three tables based on multiple conditions

Imagine three data tables A, B and C. A and B share a common variable ID1. B and C share a common variable ID2. Write a pseudo query to get this result: select everything from Table B, with matching records in both Table A and B, but not in Table C.

My version of the answer is below (but I am not sure if it's correct):

Select *
From table_b
Left Join table_a
On table_b.ID1 = table_a.ID1
Where table_b.ID2 NOT IN table_c.ID2

I am very skeptical about if the Where condition would work for the given condition? Please give your opinion on my answer. Thanks!

Select *
From table_b
Left Join table_a On table_b.ID1 = table_a.ID1
Where not exists (select * from table_c where table_c.ID2 = table_b.ID2)

Similar to IngoB's solution but slightly more readable (IMHO)

SELECT *
FROM table_b 
LEFT OUTER JOIN table_a USING (id1)
WHERE id2 NOT IN (SELECT id2 FROM table_c)

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