wiredmark
wiredmark

Reputation: 1108

Simple UPDATE SQL Query

I'm doing a work for a client but since I haven't been using PHP/MySQL for a while I forgot some simple things, hope you can help me out.

I have the following SQL table:

ID (non-null, autoincrement) | credit (int)

My query should put the whole "credit" column to 0 except for the row that has the higher ID.

So I would do:

UPDATE $table SET credit = 0 WHERE... ?

Thanks in advance for any help :)

Upvotes: 0

Views: 124

Answers (1)

Fluffeh
Fluffeh

Reputation: 33512

UPDATE $table SET credit = 0 WHERE ID > $ID

Will update any rows that have and ID greater than the variable $ID

If you only want to update the row with the maximum ID then use:

UPDATE $table SET credit = 0 WHERE ID = (select max(id) from $table)

Edit: As Eggyal correctly points out MySQL doesn't like a subquery on the same table as an update - but you can get around it nicely:

UPDATE $table 
    SET credit = 0 
    WHERE 
        credit='$credit' 
        AND statid='$statid' 
        AND userid='$userid' 
        AND ID = (select ID from (SELECT MAX(ID)as ID from $table) a)

And examples from my console:

mysql> select * from first;
+------+-------+
| id   | title |
+------+-------+
|    1 | aaaa  |
|    2 | bbbb  |
|    3 | cccc  |
|    4 | NULL  |
|    6 | eeee  |
+------+-------+
5 rows in set (0.00 sec)

mysql> update first set title='ffff' where id=(select max(id) from first);
ERROR 1093 (HY000): You can't specify target table 'first' for update in FROM clause

mysql> update first set title='ffff' where id=(select ID from (select max(id) as ID from first) a);
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from first;
+------+-------+
| id   | title |
+------+-------+
|    1 | aaaa  |
|    2 | bbbb  |
|    3 | cccc  |
|    4 | NULL  |
|    6 | ffff  |
+------+-------+
5 rows in set (0.00 sec)

Note: As the subquery within a subquery trick unlocks the original table, it is a good idea to run this within a transaction - if the table is unlocked from a query, it might have changed by the time it is updated - so it will be a good idea to use this type of query within a transaction.

Upvotes: 2

Related Questions