从 MySQL table select 一行或多行并从每一行更新列

From a MySQL table select one or more rows and update columns from each one

我有一个 table 和预先存在的赠品代码,我需要 select 一行或多行,然后用个人身份、客户代码和“保留”更新每行的三列“ 状态。这是为了保留每一行,直到收到我们客户的 API.

的回复

table 看起来像这样:

code               identification    customer_code    status
-----------------------------------------------------------------
81Ow3tCs1nNwxKu    --                --               available
I1NdH9F22S7RhU3    --                --               available
Xc942LWe8Z6nt8x    --                --               available
zcLMRO8kSeM7S06    --                --               available
K94erORvzSsU0ik    --                --               available

尝试过这个但出现错误:

UPDATE promo_codes 
SET 
    identification='12345',
    customer_code='67890',
    status='reserved' 
FROM 
(SELECT code FROM promo_codes WHERE status='available' LIMIT 2);

然后我尝试使用 REPLACE INTO 但也出现错误:

REPLACE INTO promo_codes(identification,customer_code,status)
VALUES('12345','67890','reserved')
WHERE
(SELECT code FROM promo_codes WHERE status='available' LIMIT 2);

我不知道还能做什么。有人可以给我一个主意吗? 非常感谢您的帮助。

稍微重写一下,您的代码就可以工作了

您应该考虑添加一个 ORDER BY RAND() ,因为没有订单的 LIMIT 是毫无意义的

CREATE TABLE promo_codes  (
  `code` VARCHAR(15),
  `identification` VARCHAR(20),
  `customer_code` VARCHAR(20),
  `status` VARCHAR(9)
);

INSERT INTO promo_codes 
  (`code`, `identification`, `customer_code`, `status`)
VALUES
  ('81Ow3tCs1nNwxKu', '--', '--', 'available'),
  ('I1NdH9F22S7RhU3', '--', '--', 'available'),
  ('Xc942LWe8Z6nt8x', '--', '--', 'available'),
  ('zcLMRO8kSeM7S06', '--', '--', 'available'),
  ('K94erORvzSsU0ik', '--', '--', 'available');
UPDATE promo_codes 
SET 
    identification='12345',
    customer_code='67890',
    status='reserved' 
WHERE status='available' LIMIT 2;
SELECT * FROM promo_codes
code            | identification | customer_code | status   
:-------------- | :------------- | :------------ | :--------
81Ow3tCs1nNwxKu | 12345          | 67890         | reserved 
I1NdH9F22S7RhU3 | 12345          | 67890         | reserved 
Xc942LWe8Z6nt8x | --             | --            | available
zcLMRO8kSeM7S06 | --             | --            | available
K94erORvzSsU0ik | --             | --            | available

db<>fiddle here