mysql - 如何仅更新从多个重复行中找到的第一行

问题描述

这是我拥有的,2 个表,我想用第一个表中的库存更新表 #2,但我只想更新每个重复项的第一行。

+----+------+
|code|stock |
+----+------+
|5001| 40   |
|5002| 20   |
|5003| 60   |
+----+------+

+----+------+----+
|code|stock |lot |
+----+------+----+
|5001|      | A  | < Update this
|5001|      | B  |
|5002|      | C  | < Update this
|5003|      | D  | < Update this
|5003|      | E  |
+----+------+----+

所以这里我在两行或更多行上有相同的产品,我只想更新 lot:A、lot:c 和 lot:D 中的一个,使用第一个表中的值。

我该怎么做?

解决方法

您可以尝试使用带有 join 的更新

update table2 t2
inner join  (
    select code,min(lot) lot 
    from table2
) t on t2.code  = t.code and t2.lot = t.lot
inner join table1 t1 on t2.code = t1.code 
set s2.stock = t1.stock