简体   繁体   中英

is it possible to have a union and a outer join together?

So my issue here is the 'ON' clause will not meet the delete condition if people get delete out of the source tables. Is there a way to do a outer join on the union to include if anything gets deleted for the delete part to work? This something that would run ever 5 minutes. Sorry if this is a bad example of what im trying to do.

merge into table_one ab
using ( select people,job from table_jobs
where job = 'police'
union
select b.people,b.job from second_table_jobs b
where b.job = 'firefighter') zba
on (ab.people = zba.people)
update 
set 
ab.job ='firefighter'
where b.people = ab.people
and zba.job <> ab.job
delete where zba.people <> ab.people
when not matched then
insert 
(
people,
job
)
values
(
zba.people,
zba.job
)

You can run a separate DELETE statement using NOT EXISTS to keep it clean.

DELETE FROM table_one ab
WHERE  NOT EXISTS (SELECT 1
                   FROM   (SELECT people,
                                  job
                           FROM   table_jobs
                           WHERE  job = 'police'
                           UNION
                           SELECT b.people,
                                  b.job
                           FROM   second_table_jobs b
                           WHERE  b.job = 'firefighter') zba
                   WHERE  ab.people = zba.people);  

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