[英]SQL - Updating values in subset of table using values from rows in different subset of same table
Effectively, I would like to update values in a subset of an SQL table using values from an alternate subset of that same table.实际上,我想使用来自同一表的备用子集中的值来更新 SQL 表子集中的值。 Take the following dataframe representation as an example:
以下面的数据框表示为例:
Company Employee Type Value
0 X A Category A 10
1 X A Category B 5
2 X A Category C 4
3 X A Category D 0
4 X A Category E 0
5 X A Category F 0
6 X A Category G 9
7 X B Category A 15
8 X B Category B 8
9 X B Category C 6
10 X B Category D 0
11 X B Category E 0
12 X B Category F 0
13 X B Category G 7
For both Employee A and Employee B, I would like to update Value where Type is in the set (Category D, Category E, Category F) with the corresponding value in Value where Type is in the set (Category A, Category B, Category C).对于员工 A 和员工 B,我想更新类型在集合中的值(类别 D、类别 E、类别 F)与值中的相应值,其中类型在集合中(类别 A、类别 B、类别C)。 Thus my desired outcome would be as follows:
因此,我想要的结果如下:
Company Employee Type Value
0 X A Category A 10
1 X A Category B 5
2 X A Category C 4
3 X A Category D 10
4 X A Category E 5
5 X A Category F 4
6 X A Category G 9
7 X B Category A 15
8 X B Category B 8
9 X B Category C 6
10 X B Category D 15
11 X B Category E 8
12 X B Category F 6
13 X B Category G 7
What would be the most effective way of doing this in MySQL?在 MySQL 中执行此操作的最有效方法是什么? My attempt was the following:
我的尝试如下:
UPDATE new_table
SET
Value = (SELECT
Value
FROM
(SELECT
*
FROM
new_table) t
WHERE
Type IN ('Category A', 'Category B', 'Category C'))
WHERE
Type IN ('Category D', 'Category E', 'Category F');
*My real column names are different than the above, as I assume these are reserved names *我的真实列名与上述不同,因为我认为这些是保留名称
Update更新
Based on OP comments, there needs to be a Type
translation table which indicates where the new value should come from for a given category:根据 OP 注释,需要有一个
Type
转换表来指示给定类别的新值应来自何处:
UPDATE new_table t1
JOIN (SELECT 'C1' AS Cat1, 'C4' AS Cat2
UNION ALL
SELECT 'C2' AS Cat1, 'C5' AS Cat2
UNION ALL
SELECT 'C3' AS Cat1, 'C6' AS Cat2
) cats ON cats.Cat2 = t1.Type
JOIN new_table t2 ON t2.Employee = t1.Employee AND t2.Type = cats.Cat1
SET t1.Value= t2.Value
Demo on SQLFiddle SQLFiddle 上的演示
Original Answer原答案
Since you have a direct relationship between the Type
values, you can take advantage of that in your update query by JOIN
ing new_table
to itself where the difference in Type
is 3 and updating Value
from the JOIN
ed table:由于您在
Type
值之间有直接关系,因此您可以在更新查询中利用这一点,方法是将new_table
JOIN
到自身,其中Type
的差异为 3 并从JOIN
ed 表更新Value
:
UPDATE new_table t1
JOIN new_table t2 ON t2.Employee = t1.Employee AND t2.Type = t1.Type - 3
SET t1.Value= t2.Value
WHERE t1.Type in (4, 5, 6);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.