1

我有两张桌子,一张PROMOTION桌子和一张PRIZE桌子。该PRIZE表包含一个主键PRIZEID,以及另外两个字段:COSTPRIZENAME。该PROMOTION表包含几个字段以及PRIZEID将两个表链接在一起的外键。

现在我的PRIZE表包含重复的条目(重复的将是具有相同成本和奖品名称的任何行)。我想要做的是在PRIZE表中找到所有重复项,删除所有重复项(基本上为每个成本-奖品对保留一个唯一行)并更新PROMOTION表中的外键以反映这些更改。

例如,在我的奖品表中,我有

prizeid             cost             prizename
1                   100                TV
2                    50                Computer
3                   100                TV
4                    50                Computer
5                    200               Book

并且促销表包含类似的行

promotionid ...  prizeid
1                  1
2                  3
3                  2

我希望奖品桌最终看起来像这样

prizeid             cost             prizename
1                   100                TV
2                    50                Computer
5                    200               Book

和促销表看起来像

promotionid ...  prizeid
1                  1
2                  1
3                  2

我不完全确定如何进行。有任何想法吗?

提前致谢!

4

2 回答 2

2

I think you will have to do it in two steps:

(1) First, you will need to update all the entries in the PROMOTION table that points to a row that will be deleted to the equivalent row.

UPDATE promotion p SET 
    prizeid = 
        (SELECT prizeid FROM prize 
            WHERE 
                cost = (SELECT cost FROM prize WHERE prizeid = p.prizeid) 
            AND 
                prizename = (SELECT prizename FROM prize WHERE prizeid = p.prizeid) 
            ORDER BY prizeid ASC LIMIT 1
        );

(2) And then, delete all the duplicated rows from the PRIZE table.

DELETE FROM prize 
    WHERE prizeid NOT IN 
        (SELECT tab.pi FROM 
            (SELECT DISTINCT prizeid AS pi FROM prize GROUP BY prizename, cost)
        AS tab);

One way to prevent this from happening again is to make the cost and prizename be the PRIMARY KEY, instead of the prizeid.

于 2013-08-16T16:23:51.160 回答
0

假设您只想保留每个 cost + PrizeName 组合的第一个实例。你可以使用这个:

UPDATE Promotion
SET PrizeId = A.FirstPrizeIdPerCostPrizeNameCombination

FROM
    Promotion AS P 
    INNER JOIN 
    (
    SELECT 
        PrizeId, Cost, PrizeName,
        [FirstPrizeIdPerCostPrizeNameCombination] = First_Value(PrizeId) OVER (PARTITION BY Cost,PrizeName ORDER BY PrizeId)
    FROM
        Prize
    ) AS A ON A.PrizeId = P.PrizeId 
于 2013-08-16T20:35:31.140 回答