2016-02-13 50 views
0

我有許多需要刪除的重複產品。是否有查詢刪除這些「重複」與「較低的價格」和/或「相同的價格」只是保持每個產品的1?使用mysql查詢以較低的價格刪除重複產品

的重複有重複的「產品名稱」我使用Opencart的版本2.1.0.1

+0

提供表格模式(哪些字段,鍵等)。沒有這個,很難給你一個解決方案。 – Nicarus

+2

可能與問題重複[http://stackoverflow.com/questions/18932/how-can-i-remove-duplicate-rows](http://stackoverflow.com/questions/18932/how-can-i-remove -duplicate-rows) – RafaelCaballero

回答

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 
) 
; 
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; 
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; 
+0

你可以「倒轉」這個並獲得MAX而不是MIN。然後只刪除那些不是MAX的。這將處理三重複等情況。 – Nicarus

+0

上述查詢可以正常使用具有相同價格或不同價格的重複項。使用max和再次連接,以相同的名稱和必然不同的價格加入/刪除以保持「反向」查詢的良好值集合,查詢不再成功刪除具有相同價格的重複值(或倍數)。 –