gpt4 book ai didi

sql - 在删除重复行时更新具有特定 id 的表行

转载 作者:行者123 更新时间:2023-12-02 05:01:09 24 4
gpt4 key购买 nike

我有两张 table

表名:属性

attribute_id  |   attribute_name

1 attr_name_1
2 attr_name_2
3 attr_name_1
4 attr_name_2

表名:Products

product_id    |   product_name    |    attribute_id
1 prod_name_1 1
2 prod_name_2 2
3 prod_name_3 3
4 prod_name_4 4

如果你可以看到,Products 表中的attribute_id 具有以下 id 的 (1,2,3,4),而不是(1,2,1,2)

问题出在表Attribute中,即有不同ID的重复值(attribute_names),所以我想:

  1. 从表 Attributes
  2. 中选择一个重复的 ID
  3. “选择的” ID 更新表 Products(仅在 attribute_id 在表 Attributes 中具有相同名称的情况下)
  4. 然后,从 Attributes 表中删除在 Products 表中没有用处的重复值

输出:

表名:属性

attribute_id  |   attribute_name
1 attr_name_1
2 attr_name_2

表名:Products

product_id    |   product_name    |    attribute_id
1 prod_name_1 1
2 prod_name_2 2
3 prod_name_3 1
4 prod_name_4 2

演示 SQLFiddle

注意:

如果我使用 sql 而不是手动修复此问题,它将对我有很大帮助。

最佳答案

update Products
set attribute_id = (
select min(attribute_id)
from Attributes a
where a.attribute_name=(select attribute_name from Attributes a2 where a2.attribute_id=Products.attribute_id)
);


DELETE
FROM Attributes
WHERE attribute_id NOT IN
(
SELECT MIN(attribute_id)
FROM Attributes
GROUP BY attribute_name
);

关于sql - 在删除重复行时更新具有特定 id 的表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17085518/

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