7
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

我在这里哪里做错了?

4

3 回答 3

13

如果您正在寻找 MySQL 的解决方案,那么您可以使用适当的多表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_产品 |
|-------|------------|
| 3 | 2 |
| 7 | 3 |

这是SQLFiddle演示

于 2013-10-02T21:29:19.783 回答
1

尝试这个:

CREATE TABLE ps_specific_price (
  id_specific_price NUMBER,
  id_product NUMBER
);

INSERT INTO ps_specific_price (id_specific_price, id_product) VALUES (1, 2);
INSERT INTO ps_specific_price (id_specific_price, id_product) VALUES (2, 2);
INSERT INTO ps_specific_price (id_specific_price, id_product) VALUES (3, 2);
INSERT INTO ps_specific_price (id_specific_price, id_product) VALUES (4, 3);
INSERT INTO ps_specific_price (id_specific_price, id_product) VALUES (5, 3);
INSERT INTO ps_specific_price (id_specific_price, id_product) VALUES (6, 3);
INSERT INTO ps_specific_price (id_specific_price, id_product) VALUES (7, 3);

COMMIT;

DELETE FROM ps_specific_price ps
  WHERE ps.id_specific_price NOT IN (
    SELECT MAX(id_specific_price)
      FROM ps_specific_price ps_in
    WHERE ps_in.id_product = ps.id_product
    );

SELECT * FROM ps_specific_price;

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

您必须将内部查询中的表与外部查询中的表连接起来。

我正在使用 Oracle 11g R2。我在 SQLFiddle 上检查了这一点,我的 DELETE 语句对 MySQL 无效——没有安装那个,也没有太多经验,但你没有说你使用的是什么数据库。

于 2013-10-02T21:20:15.843 回答
0

也许你想尝试:

从 ps_specific_price 中删除 (id_product,id_specific_price) 不在 (SELECT id_product,MAX(id_specific_price) FROM ps_specific_price GROUP BY id_product);

我在我的 Teradata 数据库上尝试了这个,它可以工作。

在您之前的查询中,我看到您唯一想念的是映射 id_product ,它是删除集的最高价格。删除将不知道在删除之前它必须匹配 pid 和 price。

希望这可以帮助。

于 2013-10-02T21:20:39.587 回答