我必須爲每個用戶更新n個最舊的訂單。現在我用下面的代碼來更新每個用戶1條最早的記錄,但無法弄清楚如何更新N條記錄...更新每個用戶的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"
我發現anserw:
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";
限制不會幫助這裏 – user606521