MYSQL 更新单个匹配行而不是全部

MYSQL Updating single matching row instead of all

我正在与 mysql 合作,但碰壁了。请看我的 db-fiddle: https://www.db-fiddle.com/f/nhY88U8gtunUqRaSBLBTrT/0

item_storage 是一个静态 table。它创建一次,然后偶尔更新。

操作是一个动态的 table,它在操作开始时创建,并在操作完成后清除。

操作中的每一行都有唯一的ID值。例如,在操作 table 中,我只有 2 行,都有唯一的序列号。我需要根据 table.

操作更新我的 item_storage table

由于在我的操作中 table 我有 1 件序列号为“AAAAAA”的物品和 1 件带有“BBBBBB”的物品,我必须更新我的 item_storage 并设置 current_operation 和 ID与操作 table.

相同

问题是,在我的 item_storage 中,我可以有多个具有匹配序列号的项目。他们唯一的区别是不同的 Slave ID。我想随机选择(或 select 具有较低从属 ID 的那个)并仅更新一个匹配的序列项而不是更新所有项。

正如您在我的 sql fiddle 中看到的那样,序列号为“AAAAAA”的两个项目都在我的 item_storage table.[=12= 中更新了]

您使用的 MySQL 版本是什么? 我的例子是 MariaDB。 完成您所要求的一种方法是。

  1. Find the lowest SlaveID for Serial in your item_storage table
  2. Update using join adding in the where condition the SlaveID.
UPDATE item_storage
inner join 
operation 
on operation.Serial=item_storage.Serial 
SET item_storage.Current_operation = operation.Quantity, 
item_storage.ID = operation.ID 
WHERE item_storage.Slave_ID in    (
      select Slave_ID from        (
      select Slave_ID,Serial from ( 
      select Slave_ID,Serial FROM item_storage order by Slave_ID ) as a 
      group by serial             ) as b  ) 
and operation.Statusv != 'DONE';

使用此查询:

SELECT Serial, MIN(Slave_ID) Slave_ID 
FROM item_storage  
GROUP BY Serial

您在 item_storage 中得到每个 Serial 的最小值 Slave_ID

item_storage 加入上述查询并加入 operation:

UPDATE item_storage i
INNER JOIN (
  SELECT Serial, MIN(Slave_ID) Slave_ID 
  FROM item_storage  
  GROUP BY Serial
) s ON s.Slave_ID = i.Slave_ID 
INNER JOIN operation o ON o.Serial = i.Serial
SET i.Current_operation = o.Quantity, 
    i.ID = o.ID 
WHERE o.Statusv <> 'DONE';

参见demo