我正在为客户做一份工作,但由于我有一段时间没有使用PHP / MySQL,我忘记了一些简单的事情,希望你能帮助我。
我有以下SQL表:
ID (non-null, autoincrement) | credit (int)
我的查询应该将整个“credit”列放到0,除了具有更高ID的行。
所以我会这样做:
UPDATE $table SET credit = 0 WHERE... ?
提前感谢您的任何帮助:)
答案 0 :(得分:2)
UPDATE $table SET credit = 0 WHERE ID > $ID
将更新ID和ID大于变量$ID
如果您只想更新具有最大ID的行,请使用:
UPDATE $table SET credit = 0 WHERE ID = (select max(id) from $table)
编辑:正如Eggyal正确地指出MySQL不喜欢与更新相同的表上的子查询 - 但你可以很好地解决它:
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)
来自我的控制台的例子:
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)
注意:由于子查询技巧中的子查询解锁了原始表,因此最好在事务中运行它 - 如果表是从查询中解锁的,它可能在更新时发生了更改 - 所以在事务中使用这种类型的查询是个好主意。