我必须为每个用户更新 n 个最旧的订单。现在我使用以下代码更新每个用户 1 条最旧的记录,但不知道如何更新 n 条记录......
UPDATE orders
INNER JOIN (
SELECT id, MIN(created) AS created
FROM orders
WHERE status="queue" AND type="order"
GROUP BY user_id
) m ON orders.id = m.id
SET orders.status = "process",
orders.lock_id ="somehash"
我找到了答案:
set @num := 0, @type := "";
UPDATE orders INNER JOIN(
SELECT id, user_id, created, row_number FROM (
SELECT id, user_id, created,
@num := if(@type = user_id, @num + 1, 1) AS row_number,
@type := user_id AS dummy
FROM orders
WHERE status = "queue"
ORDER BY user_id, created asc ) AS grouped_orders
WHERE grouped_orders.row_number <= 2
) m ON orders.id = m.id SET orders.status = "process", orders.lock_id = "somehash";