日期:2014-05-17  浏览次数:20483 次

求SQL:两表关联 删除不匹配的数据
式样如下:

1.主表A和参照表B,都有s,d两个字段
2.A,B两表关联查询,表B不存在的数据从表A插入到表C,然后从表A中删除。

insert C values (select * from A,B where A.g=1 and (a.s=B.s or a.d=B.d))

delete from B where not exsits (select * from A,B where A.g=1 and (a.s=B.s or a.d=B.d))

意思如上所示,求一正确SQL。

先谢谢各位大虾了。

------解决方案--------------------
SQL code
insert C select * from A,B where A.g=1 and (a.s=B.s or a.d=B.d)

------解决方案--------------------
SQL code
delete from B 
where not exists (select * from A where A.g=1 and (a.s=B.s or a.d=B.d))

------解决方案--------------------
SQL code
insert into C (Col1,Col2)
select a.Col1,b.Col2 
from A,B where A.g=1 and (a.s=B.s or a.d=B.d)

--列名和列的顺序不一致时,需要指定

------解决方案--------------------
SQL code

insert into C 
select A.* 
from A 
left join B on a.s=B.s or a.d=B.d
where A.g=1 and (B.s is null or B.d is null)

delete from A 
where A.g=1 and 
not exsits (select * from B where (a.s=B.s or a.d=B.d))

------解决方案--------------------
SQL code
delete from b where not exists (select * from A where A.g=1 and (a.s=B.s or a.d=B.d))

------解决方案--------------------
确认你的需求跟伪SQL的逻辑一致吗? 我估计有出入..
SQL code

insert into C 
select A.* 
from A
left join B on a.s<>B.s or a.d<>B.d
where A.g=1 and (B.s is null or B.d is null)

delete from A 
where A.g=1 and 
not exsits (select * from B where (a.s<>B.s or a.d<>B.d))

------解决方案--------------------
2.A,B两表关联查询,表B不存在的数据从表A插入到表C,然后从表A中删除。
SQL code
insert C select * from A where not exists( select 1 from B where  a.s=B.s or a.d=B.d)and  a.g=1

------解决方案--------------------
探讨

引用:
2.A,B两表关联查询,表B不存在的数据从表A插入到表C,然后从表A中删除。

SQL code
insert C select * from A where not exists( select 1 from B where a.s=B.s or a.d=B.d)and a.g=1



SQL code
delete A where……