mysql - 更新查询中的强制转换函数出现问题

标签 mysql sql mysql-5.6

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

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 这是 fiddle http://sqlfiddle.com/#!9/420d7f 的链接

最佳答案

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

但郑重声明,该错误是因为您在语法不支持的位置使用了INTEGER

好的:

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

错误:

CAST(<expr> AS INTEGER)

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

关于mysql - 更新查询中的强制转换函数出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60511612/

相关文章:

php - URL包含参数时无法在查看页面显示结果

mysql - 表达这段代码的更简洁的方式是什么?

php - ajax返回成功但mysql数据库未更新

php - 使用给定的变量名称将前三个结果保存在 while 循环中?

MySQL 5.7.10 简单查询比 5.6.35 慢

PHP5 MySQL5 PDOException “could not find driver”

mysql - 提高 MySQL 查询性能

php - 如何在SQL中合并不同表的数据

mysql - 如何仅使用 SQL 实现动态 WHERE 子句? (我不能使用任何编程语言字符串连接)

mysql - 全文搜索 Innodb 失败,MyIsam 返回结果