简体   繁体   中英

SQL Query, how to get all elements from one list and only the similar ones from another table

I have 2 tables, and they have PartIDs as their similarity to branch them. I need to pull 3 columns from the first table and 2 columns from Table 2.

The problem I am having is that Table 1 sometimes has more or different PartIDs than Table 2 and that is OK. In a third table I want to be able to have a query that can run and give me all the PartIDs from the first table and second table even if they dont exist in the other one. But if they exist in both I would like the data to be together as it normally is

This code shows the PartIDs that are similar between both Tables:

SELECT `Sheet1$`.ENSPIECEID, `Sheet1$`.`Part Number`, `Sheet1$`.Description,`Sheet1$`.TITRETYPE, `Sheet1$`.Utilization, `Sheet2$`.Notes, `Sheet2$`.Justification
FROM `Sheet1$` `Sheet1$`, `Sheet2$` `Sheet2$`
WHERE `Sheet1$`.ENSPIECEID = `Sheet2$`.ENSPIECEID

I need this so that I can flag which PartIDs are coming only from 1st sheet and which only from 2nd Sheet.

You could do this (you will have to replace with your table and column names):

For this example I have used test table structure of: See it here

tab1 (partid int, description varchar(100))
tab2 (partid int, variation varchar(100))

To select the part ids in both tables

select *
from tab1 t1
join tab2 t2 on t1.partid = t2.partid;

To select the part ids where only in the first table

select * 
from tab1 t1
left outer join tab2 t2 on t1.partid = t2.partid
where variation is null;

To select the part ids where only in second table

select * 
from tab2 t2
left outer join tab1 t1 on t2.partid = t1.partid
where description is null;

And so to select all the part ids where not in the other table, union the results of the last two queries

select t1.partid 
from tab1 t1
left outer join tab2 t2 on t1.partid = t2.partid
where variation is null
union
select t2.partid 
from tab2 t2
left outer join tab1 t1 on t2.partid = t1.partid
where description is null;
SELECT `Sheet1$`.ENSPIECEID, `Sheet1$`.`Part Number`, `Sheet1$`.Description,`Sheet1$`.TITRETYPE, `Sheet1$`.Utilization, `Sheet2$`.Notes, `Sheet2$`.Justification
FROM `Sheet1$` `Sheet1$`
LEFT JOIN `Sheet2$` `Sheet2$` on `Sheet1$`.ENSPIECEID = `Sheet2$`.ENSPIECEID

would return all records from sheet1 and only those in sheet 2 that match; assuming there are no other syntax errors.

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