Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
85 views
in Technique[技术] by (71.8m points)

sql - How can I extract the difference from two queries?

Using SQL Server.

I have one query which outputs results, and another that does the same. Id like to output what the is not in the other:

select distinct 
v_GS_PC_BIOS.SerialNumber0
from v_GS_PC_BIOS
JOIN v_R_System ON v_R_System.ResourceID  = v_GS_PC_BIOS.ResourceID
WHERE v_GS_PC_BIOS.ResourceID NOT IN 
(
    SELECT distinct v_R_System.ResourceID from v_r_system
)

OR

Select distinct
v_R_System.ResourceID
from v_R_System
WHERE v_R_System.ResourceID NOT IN 
(
    select distinct 
    v_GS_PC_BIOS.SerialNumber0
    from v_GS_PC_BIOS
    JOIN v_R_System ON v_R_System.ResourceID  = v_GS_PC_BIOS.ResourceID
)

I am getting 0 results

question from:https://stackoverflow.com/questions/65891758/how-can-i-extract-the-difference-from-two-queries

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One way to compare table contents

Lets say you have 2 tables

Cars: modelid, manufacturerid, ... some more car related columns

Airplanes: modelid, manufacturerid, ... some more airplane related columns

Task: determine, which car manufacturers don't make airplanes, and vise-versa.


SELECT c.manufacturerName, 'only cars' as specialization
FROM cars c LEFT JOIN
     airplanes a ON c.manufacturerid = a.manufacturerid
WHERE a.manufacturerid IS NULL
UNION ALL
SELECT a.manufacturerName, 'only airplanes' as specialization
FROM cars c RIGHT JOIN
     airplanes a ON c.manufacturerid = a.manufacturerid
WHERE c.manufacturerid IS NULL

Results here should be like

Mazda, only cars
Toyota, only cars
Airbus, only airplanes

And companies like these should not show because their record will be in both tables

Honda, Mitsubishi, Saab, Ford, Fiat


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...