这是我的表结构:
table
.id
(自增;主键)
table
.qty
(可能的值:0 - 1000)
行数:
+----+-----+ | id | qty | +----+-----+ | 1 | 0 | | 2 | 5 | | 3 | 5 | | 4 | 10 | +----+-----+
I want to decrease the quantity available by 12. Meaning, the new result should be:
Edit: I probably should have specified all these numbers are arbitrary. They could be anything.
+----+-----+ | id | qty | +----+-----+ | 1 | 0 | | 2 | 0 | | 3 | 0 | | 4 | 8 | +----+-----+
Right now, I do the following:
SELECT id, qty FROM table WHERE qty > 0 LIMIT 12
Filter through all the data to figure out what qty to remove from each row
Use a PDO prepared statement to mass update the affected rows:
UPDATE `table` SET qty = ? WHERE id = ?`
我的问题:有没有办法在 MySQL 中完成这一切?
最佳答案
SET @q = 12;
UPDATE `table`
SET qty = CONCAT(GREATEST(qty - @q, 0), LEFT(@q := @q - LEAST(qty, @q), 0))
ORDER BY id;
查看 sqlfiddle .
关于mysql - 从数据库中的多行中删除数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10557492/