代码之家  ›  专栏  ›  技术社区  ›  Darko Miletic

更新查询中的cast函数有问题

  •  1
  • Darko Miletic  · 技术社区  · 5 年前

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

    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)'
    

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

    2 回复  |  直到 5 年前
        1
  •  2
  •   Bill Karwin    5 年前

    在这种情况下,确实不需要使用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

        2
  •  1
  •   Gordon Linoff    5 年前

    不需要 cast()

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

    如果你真的需要 转换() ,然后使用 signed unsigned

    推荐文章