简体   繁体   中英

Update table where column is MIN

I'm writing small update for home inventory which changes quantity for product which has the oldest expiration date (my way to achieve FIFO). Below is the example which I tried to execute but with no luck.

UPDATE stan
SET Ilosc=Ilosc-1
WHERE Date_exp=(SELECT MIN(Date_exp) AS Date_exp FROM stan as sta WHERE ID_Product=1)

Above example ends with following error:

1093 - Table 'stan' is specified twice, both as a target for 'UPDATE' and as a separate source for data

Can someone point me to the right direction?

MySQL does not allow you to perform an UPDATE/INSERT/DELETE on a table if you reference that table in an inner query. However, the workaround is to use a temporary table in your subquery, something like this:

UPDATE stan a
SET a.Ilosc=a.Ilosc-1
WHERE a.Date_exp =
(SELECT Date_exp from 
     (select min(date_exp) as date_exp 
      FROM stan 
      WHERE ID_Product=1) sta
);

Hope it helps.

I would just use order by and limit :

UPDATE stan
    SET Ilosc = Ilosc - 1
    WHERE id_product = 1
    ORDER BY Date_exp
    LIMIT 1;

This has two key advantages over your approach. First, it is simpler and does not require any hacks to get around MySQLs restrictions on referencing the table being updated.

Second, the logic is correct. Your code can update rows where the product id is not 1, because you have no restriction in the outer query. Multiple rows with different product ids could have the same minimum date.

If you didn't want to take this approach (say because you already have a JOIN in the UPDATE) , you can do:

UPDATE stan s JOIN
       (SELECT id_product, MIN(Date_exp) as minde
        FROM stan s2
        WHERE id_product = 1
        GROUP BY id_product
       ) s2
       ON s.id_product = s2.id_product AND s.Date_exp = s2.minde
    SET Ilosc = Ilosc - 1;

I also might throw in a condition that Ilosc > 0 if that is your intention.

UPDATE A
SET A.COLUMN_NAME=VALUE
FROM TABLE_NAME A
INNER JOIN (SELECT MIN(COLUNN_NAME) FROM TABLE_NAME)  B ON (A.COLUMN_NAME=B.COLUMN_NAME);

Try below query . and follow this link ( https://dev.mysql.com/doc/refman/5.6/en/update.html )

UPDATE stan
SET Ilosc=Ilosc-1
WHERE Date_exp=(SELECT Date_exp FROM (SELECT MIN(Date_exp) AS Date_exp FROM `stan` AS sta WHERE ID_Product = 1) AS t)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM