SQL query to achieve subtraction operation

As a basic skill, SQL is often encountered in set operations. There is nothing to say about the realization of intersection and union, but the realization of difference set is quite interesting.

Prepare data

create table a (id int, name varchar(100));
create table b (id int, name varchar(100));
insert into a values (1, 'Zhang'),(2, 'Wang'),(3, 'Li'),(4, 'Zhao');
insert into b values (2, 'Wang'),(3, 'Li');

General method

select id,name
from a
where a.id not in (select id from b);

select a.id,a.name
from a left join b
on a.id = b.id
where b.id is null;

Dedicated method

-- Oracle/ODSP/HIVE
select a.id,a.name
from a anti join b
on a.id = b.id;

-- SQL Server
select id,name from a
except
select id,name from b ;

Guess you like

Origin blog.csdn.net/ManWZD/article/details/115005678