[英]How to remove categories with no products?
I am a bit stuck on the following SQL:我有点卡在以下 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);
It removes all data ignoring the where
part.它删除所有数据而忽略
where
部分。 What am I doing wrong?我究竟做错了什么?
You need to remove the single quotes around the column name, otherwise it becomes a literal string, and the expression does not do what you want.您需要删除列名周围的单引号,否则它会变成文字字符串,并且表达式不会执行您想要的操作。 It actually checks if literal string
'category_id'
belongs to the resulset of the subquery: since it probably does not, all rows get deleted.它实际上检查文字字符串
'category_id'
是否属于子查询的结果集:因为它可能不属于,所以所有行都被删除。
Also, I would recommend using exists
, which is null
-safe, while not in
is not (that is, if any value in the subquery is null
, all rows will be deleted).另外,我建议使用
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
);
For performance, consider an index on oc_product_to_category(category_id)
(or at least a compound index where this column appears first).为了提高性能,请考虑
oc_product_to_category(category_id)
上的索引(或至少是此列首先出现的复合索引)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.