我对下面的SQL有点卡壳。
delete from oc_category_description where 'category_id' NOT in (SELECT category_id FROM oc_product_to_category);
delete from oc_category_path where 'category_id' NOT in(SELECT category_id from oc_product_to_category);
delete from oc_category_to_store where 'category_id' NOT in(SELECT category_id from oc_product_to_category);
delete from oc_category_to_layout where 'category_id' NOT in(SELECT category_id from oc_product_to_category);
delete from oc_category_filter where 'category_id' NOT in(SELECT category_id from oc_product_to_category);
delete from oc_coupon_category where 'category_id' NOT in(SELECT category_id from oc_product_to_category);
delete from oc_category where 'category_id' NOT in(SELECT category_id from oc_product_to_category);
它删除了所有数据,忽略了 where
部分。我到底做错了什么?
你需要去掉列名周围的单引号,否则它就会变成一个文字字符串,而这个表达式并不能达到你想要的效果。实际上,它检查的是文字串是否为 'category_id'
属于子查询的resulset:因为它可能不属于,所以所有的记录都会被删除。
另外,我建议使用 exists
,也就是 null
-安全,而 not in
不是(也就是说,如果子查询中的任何值是 null
,所有的行将被删除)。)
delete from oc_category
where not exists (
select 1
from oc_product_to_category pc
where pc.category_id = oc_category.category_id
);
为了保证性能,可以考虑在 oc_product_to_category(category_id)
(或至少是本列先出现的复合索引)。