gpt4 book ai didi

mysql - 使用 GROUP BY 删除重复项的查询

转载 作者:可可西里 更新时间:2023-11-01 06:40:34 25 4
gpt4 key购买 nike

id_specific_price    id_product  
-------------------------------
1 2
2 2
3 2
4 3
5 3
6 3
7 3

需要删除重复项,预期结果:

id_specific_price    id_product  
-------------------------------
3 2
7 3

SELECT * 
FROM ps_specific_price
WHERE id_specific_price NOT IN
(SELECT MAX(id_specific_price)
FROM ps_specific_price
GROUP BY id_product)

有效但是

DELETE FROM ps_specific_price 
WHERE id_specific_price NOT IN
(SELECT MAX(id_specific_price)
FROM ps_specific_price
GROUP BY id_product)

没有。有很多例子可以解决这个问题,但出于某种原因我无法适应它。我相信这是 GROUP BY。例如:

DELETE FROM ps_specific_price 
WHERE id_specific_price NOT IN
(SELECT MAX(p.id_specific_price)
FROM (SELECT * FROM ps_specific_price ) as p)
GROUP BY id_product

我哪里错了?

最佳答案

如果您正在寻找 MySQL 的解决方案,那么您可以使用合适的 multi table DELETE语法以及像这样的 JOIN

DELETE p
FROM ps_specific_price p JOIN
(
SELECT id_product, MAX(id_specific_price) id_specific_price
FROM ps_specific_price
GROUP BY id_product
) d
ON p.id_product = d.id_product
AND p.id_specific_price <> d.id_specific_price;

结果:

| ID_SPECIFIC_PRICE | ID_PRODUCT ||-------------------|------------||                 3 |          2 ||                 7 |          3 |

这是 SQLFiddle 演示

关于mysql - 使用 GROUP BY 删除重复项的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19146794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com