我有大约 30k 个产品从 API 自动导入到 WooCommerce。API 存在一个错误,最终导致为大多数商品添加重复的产品,但现在我只剩下 30k 多个产品,而不是 15k 个产品。
我无法手动检查并删除每个重复项,我一直在尝试编写一个可以执行此操作的 SQL 脚本,但由于 WordPress 中存储了所有不同的数据,这使得它变得复杂。
看起来这个脚本获取了所有唯一的行,但没有获取重复的行。
SELECT meta_value, meta_key, count(*)
FROM wp_postmeta WHERE meta_key LIKE '_sku'
GROUP BY `meta_value`
Run Code Online (Sandbox Code Playgroud)
所以我想要做的是找到所有行,其列的列中meta_key = _sku有重复的行,称为列中的值meta_value
例如,如果我有一些像这样的行:
meta_id post_id meta_key meta_value
1504098 57049 _sku 26785030612
1504135 57051 _sku 26785030612
1503993 57045 _sku 26785033309
Run Code Online (Sandbox Code Playgroud)
我希望它看起来像这样:
meta_id post_id meta_key meta_value
1504135 57051 _sku 26785030612
1503993 57045 _sku 26785033309
Run Code Online (Sandbox Code Playgroud)
所以我需要根据meta_value中的值删除第一行。
我刚刚为朋友解决了这个问题。我们尝试删除使用 WooCommerce 插件的 WordPress 网站的重复 SKU。
以下是查找所有重复 SKU 及其 ID 的查询:
# CHECK QUERY
# Use this query to get a list of post_ids and old and new skus...
# we wanted to keep the latest sku so we wanted to delete
# the older duplicate meta records
select * from (
select post_id, min(meta_id) as deletethis, max(meta_id) as keepthis, meta_value, meta_key, count(*) as c from wp_postmeta
where meta_key like '_sku'
and meta_value is not null
and meta_value != ''
group by `meta_value`
) as skus where c > 1
Run Code Online (Sandbox Code Playgroud)
以下是删除重复 SKU ID 的查询。我们希望查询删除重复项,以便任何非 sku 相关元条目不受影响。
# DELETE QUERY
# Use this query to delete the older sku record and keep
# the newer sku record
delete from wp_postmeta where meta_id in (
select skus.deletethis from (
select min(meta_id) as deletethis, max(meta_id) as keepthis, meta_value, meta_key, count(*) as c from wp_postmeta
where meta_key like '_sku'
and meta_value is not null
and meta_value != ''
group by `meta_value`
) as skus where c > 1
);
Run Code Online (Sandbox Code Playgroud)