使用mysql查询以较低的价格删除重复的产品

时间:2016-02-13 07:13:08

标签: mysql sql opencart2.x

我有很多需要删除的重复产品。是否有一个查询删除这些“重复”与“较低价格”和/或“相同价格”只是保持每个产品1?

重复项有重复的“产品名称”我正在使用Opencart版本2.1.0.1

3 个答案:

答案 0 :(得分:1)

由于您使用的是mysql,因此需要使用连接(不支持分区):

选择:

select p.* 
from products as p 
join 
(
    select name, min(price) as price 
    from products group by name having count(price) = 2
) as p2 on p2.name = p.name and p2.price = p.price;

获取所有重复产品的最低价格(其中重复数据假定同一产品恰好有两行)。

要删除,请将初始选择更改为删除,如下所示:

delete p.* 
from products as p 
join 
(
    select name, min(price) as price 
    from products group by name having count(price) = 2
) as p2 on p2.name = p.name and p2.price = p.price;

答案 1 :(得分:0)

没有太多信息(哪个RDBMS等)我只能推测这个解决方案对你有用:

WITH Flagged AS
(
SELECT
    ProductName,
    CASE WHEN ROW_NUMBER() OVER(PARTITION BY ProductName ORDER BY Price DESC) = 1 THEN 0 ELSE 1 END AS Delete
FROM
    Products
)

DELETE p
FROM Products p
JOIN Flagged f
ON (p.ProductName = f.ProductName)
WHERE f.Delete = 1;

答案 2 :(得分:0)

根据http://wiki.opencarthelp.com/doku.php?id=databse_schema上的架构,只有一种语言,下面的查询应解决您的问题:

delete p1 
from product p1
join product_description d1 on d1.product_id = p1.product_id
join product_description d2 
  on  d2.product_id <> d1.product_id
  and d2.language_id = d1.language_id
  and d2.name = d1.name
join product p2 on p2.product_id = d2.product_id
where d1.language_id = 1 -- define the language used for product name
  and (p2.price > p1.price -- delete if higher price exists
    or p2.price = p1.price and p2.product_id < p1.product_id -- delete if same price with lower id exists
  )
;