我正在为一个客户工作,但由于我已经有一段时间没有使用PHP/MySQL了,我忘记了一些简单的事情,希望你能帮助我。
我有以下SQL表:
ID (non-null, autoincrement) | credit (int)我的查询应该将整个"credit“列设置为0,但ID较高的行除外。
所以我会这么做:
UPDATE $table SET credit = 0 WHERE... ?提前感谢您的帮助:)
发布于 2012-08-27 18:16:56
UPDATE $table SET credit = 0 WHERE 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)注意:由于子查询中的子查询将解锁原始表,因此最好在事务中运行此技巧-如果表从查询解锁,则在更新时它可能已经更改-因此在事务中使用这种类型的查询将是一个好主意。
https://stackoverflow.com/questions/12140065
复制相似问题