10条数据,通过SQL语句保留id为2和7的,其他都删除,怎么实现?

如题所述

第1个回答  2013-04-10
你如果需要连表删除 ,必须先删除 子表 ,
delete from childTable a,parentTable b

where a. fk= b.id and b.id not in ('2','7');

然后再删除 父表
delete from table
where id not in ('2','7')
第2个回答  2013-04-10
delete from table
where id not in ('2','7')追问

这种情况下在单表下是可以的,如果是有外键联系的情况下就会出错啊!怎么办

追答

有外键的话 需要先删除外键的数据 才能再删除主表的数据 比如外键到table2

delete from table2
where exists (select 1 from table where table2.id=table.id and table.id not in ('2','7'))

本回答被提问者采纳
相似回答