如何把exists 转成 not exists 达到同样的效果?
CREATE TABLE table1(
co1 varchar (100))
CREATE TABLE table2(
co2 varchar (100))
INSERT INTO table1 (co1) VALUES( 'abc ')
INSERT INTO table1 (co1) VALUES( 'abc ')
INSERT INTO table1(co1) VALUES( 'aab ')
INSERT INTO table1 (co1) VALUES( 'bbc ')
-------如何把exists 转成 not exists 达到同样的效果?
IF EXISTS (SELECT 1 FROM table1 WHERE table1.co1 NOT IN (SELECT * FROM table2))
BEGIN
INSERT INTO table2 (co2) SELECT DISTINCT co1 FROM table1 WHERE table1.co1 NOT IN (SELECT * FROM table2)
END
------解决方案--------------------CREATE TABLE table1(co1 varchar(100))
CREATE TABLE table2(co2 varchar(100))
INSERT INTO table1 select 'abc '
union all select 'aab '
union all select 'bbc '
union all select 'dub '
union all select '1ub '
INSERT INTO table2 select 'dub '
union all select 'aab '
select * from table1
select * from table2
IF not EXISTS(select 1 from table1 a inner join table2 b on a.co1=b.co2 group by a.co1 having(count(distinct a.co1)=(select count(distinct co1) from table1)))
BEGIN
INSERT INTO table2(co2) SELECT DISTINCT co1 FROM table1 WHERE co1 NOT IN (SELECT co2 FROM table2)
END
select * from table2
drop table table1,table2