mysql 将行更新为之前的枚举值

mysql update row to previous enum value

我有一个简单的 MYSQL table,有 2 列:

id | status
 1 |  b

statusENUM('a','b','c')

我想更新这一行,如果:

1) 当前状态为 c 然后新值 b

2) 当前状态为 b 然后新值 a

3) 当前状态是a 那么什么都不做

我尝试了以下但当然不起作用:

UPDATE table SET status = status - 1 WHERE id = '1'
UPDATE tablename SET status = case status when 'b' then 'a'
                                          when 'c' then 'b' end
WHERE id = '1' and status <> 'a'

WHERE 中的<> 'a' 是为了避免事务中出现 'a' 行。)

这样试试:

update table_name
set status = case when status = 'c' then 'b'
                  when status = 'b' then 'a'
                  when status = 'a' then 'a'
             end
 where id = 1;

MySQL 具有枚举类型的索引值,因此您执行 status = status - 1 的方法是一个很好的方法。

正如 manual 所说:

Each enumeration value has an index:

  • The elements listed in the column specification are assigned index numbers, beginning with 1.
  • The index value of the empty string error value is 0. This means that you can use the following SELECT statement to find rows into which invalid ENUM values were assigned: SELECT * FROM tbl_name WHERE enum_col=0;
  • The index of the NULL value is NULL.
  • The term “index” here refers to a position within the list of enumeration values. It has nothing to do with table indexes.

因此在您的情况下,这些是索引值:

  • 空:空
  • ''(空):0
  • 'a': 1, 'b': 2, 'c': 3

基于此,可以简单的写成:

update table set status=status-1 where status>1 and id=1;