现在有两张表table1,和table2,table1只有字段A,table2有字段B和一个字段C字段A和字段B数据类型是一样的现在想在table2的字段C中插入数值,如果字段B在字段A中存在相同的值,字段C的值为0字段B有这个值,而字段A没有这个值,字段C的值为1字段A有这个值,而字段B没有这个值,字段C的值为2可能说点有点不明白其实就是表1,表2两表,如果表1的某一个字段有某一个值,表2中没有相应的字段没有,就在表2中的另外一个字段标示一下就这样请问有没有高手提示一下,如果有sql语句就更好了非常感谢...
set c = (case when exists (select 1 from tb1 where tb1.a = tb2.b) then 0 else 1 end)
from tb2
2.字段B有这个值,而字段A没有这个值,字段C的值为1
3.字段A有这个值,而字段B没有这个值,字段C的值为2以上条件中,条件1是没有问题的;条件2和条件3是矛盾的,可以有两种理解:
第一种理解是,两个条件是等价的,也就是说c字段要么是1要么是2,c字段不会同时出现1和2,这样sql语句为:update tb2
set c = (case when exists (select 1 from tb1 where tb1.a = tb2.b) then 0 else 1 end)
from tb2第二种理解是:正常理解条件2,而对于条件3,则是:“在table2中添加一条数据,字段b为table1的字段a,字段c为数值2”,sql语句为:update tb2
set c = (case when exists (select 1 from tb1 where tb1.a = tb2.b) then 0 else 1 end)
from tb2insert into tb2
select A,2
from(
select a from tb1 except select b from tb2
) t
set @id=12--设置插入值
update tb2 set c=(case when exists(select 1 from tb where a=@id) and exists(select 1 from tb2 where b=@id) then 0 when not exists(select 1 from tb where a=@id) and exists(select 1 from tb2 where b=@id) then 1 when exists(select 1 from tb where a=@id) and not exists(select 1 from tb2 where b=@id) then 2 end )