1

Here is my table structure:
table.id (auto increment; primary key)
table.qty ( possible values: 0 - 1000 )

Rows:

+----+-----+
| 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 = ?`
    

My question: Is there a way to do this all in MySQL?

4

1 に答える 1

5
SET @q = 12;

UPDATE `table`
SET qty = CONCAT(GREATEST(qty - @q, 0), LEFT(@q := @q - LEAST(qty, @q), 0))
ORDER BY id;

See it on sqlfiddle.

于 2012-05-11T19:33:21.690 に答える