1

我有一个(mysql)数据库表,其中包含以下列:

NAME | String (Unique)

STATUS | int

UPDATE_COUNT | int (Unique)

我希望 Max(UPDATE_COUNT) 的值反映对表中的行执行的更新的累积次数。例如,从一个空表开始:

Insert - (Name=John, Status=0) -  // update count on that row is set to 1

Insert - (Name=Mary, Status=0) -  // update count on that row is set to 2

Update - (Name=John, Status=1) -  // update count on that row is set to 3

Update - (Name=Mary, Status=2) -  // update count on that row is set to 4

ETC..

因此,对于任何行,无论是更新还是插入,每行插入或更新的更新计数值为 max(update_count) + 1。

这个想法是“从 mytable 中选择 max(update_count)”结果表示执行的插入/更新的总数。

我想编写自动增加 update_count 值的插入和更新 sql 语句,例如:

"UPDATE MYTABLE SET STATUS=1,UPDATE_COUNT=(SELECT MAX(UPDATE_COUNT) FROM MYTABLE) WHERE NAME IN ('John', 'Mary')"

但是这不是有效的 sql,更新语句我不包含从同一个表中选择的 from 子句,mysql 中的错误是:

"You can't specify target table 'MYTABLE' for update in FROM clause"

有关如何规避此限制的任何建议?

4

1 回答 1

2

刚刚在优秀的 Xaprb 博客上找到了以下解决方案:

http://www.xaprb.com/blog/2006/06/23/how-to-select-from-an-update-target-in-mysql/

于 2009-02-17T10:40:33.067 回答