更新查询中的转换功能问题

问题描述 投票:0回答:2

这是一个简单的表和测试数据,我将用来演示我的问题:

create table foo(
  id INTEGER AUTO_INCREMENT PRIMARY KEY,
  orderpos int not null
);

insert into foo (orderpos) values (1);
insert into foo (orderpos) values (2);
insert into foo (orderpos) values (3);
insert into foo (orderpos) values (4);
insert into foo (orderpos) values (5);

我想使用类似的查询来更新某些字段:

update foo
set orderpos = 
        CAST( 
        CASE 
          WHEN id = 2 THEN 4
          WHEN id = 3 THEN 8
         END
         AS INTEGER 
        )  
where id in(2, 3);

但是我得到了错误

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INTEGER 
        )  
where id in(2, 3)'

我知道删除CAST查询会起作用,但我想了解为什么不允许此操作?

MySQL是5.6这是小提琴http://sqlfiddle.com/#!9/420d7f

的链接
mysql sql mysql-5.6
2个回答
0
投票

不需要cast()。只需使用:

set orderpos = (CASE WHEN id = 2 THEN 4
                     WHEN id = 3 THEN 8
                END)

如果您确实需要cast(),请使用signedunsigned


0
投票

的确,在这种情况下,您不需要使用CAST()。

但是出于记录,错误是因为您在语法不支持的位置使用INTEGER

确定:

CAST(<expr> AS SIGNED)
CAST(<expr> AS SIGNED INTEGER)
CAST(<expr> AS UNSIGNED)
CAST(<expr> AS UNSIGNED INTEGER)

WRONG:

CAST(<expr> AS INTEGER)

请参阅CAST()CONVERT()的文档以了解受支持的数据类型语法:https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html

© www.soinside.com 2019 - 2024. All rights reserved.