mysql - 从数据库中的多行中删除数量

标签 mysql

这是我的表结构:
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:

  1. SELECT id, qty FROM table WHERE qty > 0 LIMIT 12

  2. Filter through all the data to figure out what qty to remove from each row

  3. 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/

相关文章:

php - 尝试清理用户输入以动态设置 PearDB 准备语句中的列名称

mysql - 在 Django 1.4.20 中不断获取 'Too many connections'

php - 如何从特定日期起 30 天内获取确切日期?

mysql - 强制hibernate在MySQL中以单次插入的方式插入批处理数据

mysql - 无论我做什么,Vaadin的combobox.select()都不起作用

php - 对表进行排序并获取行位置 Laravel eloquent

mysql - Sql 语句 order by with 条件?

mysql选择如果字段行为空白替换同表上另一个字段的数据

php - MySQL 重复键更新 + 受影响的行数

Mysql字符串拆分