Select data from one table depending on the results of another select SQL Server

1rhkuytd  于 2023-10-15  发布在  SQL Server
关注(0)|答案(2)|浏览(152)

I have two tables that I need to compare to find records that are not in one table. My SQL so far is,

SELECT ORD_NAME FROM ERP_IMPORT_COMP
EXCEPT
SELECT NAME FROM OR_ORDER

This returns the ORD_NAME's of the records I want, but I would like to select all the fields in ERP_IMPORT_COMP WHERE they don't exist in OR_ORDER, matching by ORD_NAME=NAME. Is that possible?

Thanks.

vs3odd8k

vs3odd8k1#

This looks like you need to use not exists

select *
from ERP_IMPORT_COMP c
where not exists (
  select * from OR_ORDER o
  where o.NAME = c.ORD_NAME 
);
bweufnob

bweufnob2#

This is a classic case for a left join

SELECT I.ORD_NAME 
FROM ERP_IMPORT_COMP I
LEFT JOIN OR_ORDER O ON O.NAME = I.ORD_NAME 
WHERE O.NAME IS NULL

相关问题