2

我在选择中有一个别名,如下所示:

SELECT
    CASE ....
    WHEN 1 THEN somefield * -10
    WHEN 0 THEN somefield * 10
    END as myAlias
FROM
    ....

问题是,在 mysql 寻找的第一条记录中,它将“myAlias”标记为 UNSIGNED,但在下一条记录中,相同的别名会产生一个 SIGNED 整数,然后出现错误:

BIGINT UNSIGNED value is out of range in....

那么,如何在mysql执行任何操作之前告诉mysql“myAlias”是一个签名整数?

谢谢!

编辑:

我试过了

SELECT
    CAST(CASE ....
    WHEN 1 THEN somefield * -10
    WHEN 0 THEN somefield * 10
    END AS SIGNED) as myAlias
FROM
    ....

没有成功!

4

2 回答 2

4

我假设您表中的字段被声明为UNSIGNED INTEGER. 在这种情况下,您必须在表达式的THEN子句中键入强制转换字段。CASE下面的示例说明了一个示例。

创建并插入脚本:

CREATE TABLE mytable
(
     numberfield INTEGER UNSIGNED
   , bitfield BIT
);

INSERT INTO mytable (numberfield, bitfield) VALUES
  (134, 1),
  (673, 0),
  (855, 1),
  (133, 0),
  (778, 1),
  (234, 0);

在 THEN 子句中键入转换字段:SQL Fiddle Demo

SELECT
    CASE bitfield
        WHEN 1 THEN CAST(numberfield AS SIGNED) * -10
        WHEN 0 THEN CAST(numberfield AS SIGNED) * 10
    END as myAlias
FROM mytable

输出

MYALIAS
-------
-1340
6730
-8550
1330
-7780
2340

编写上述查询的另一种方法:SQL Fiddle Demo

SELECT
    CAST(numberfield AS SIGNED) * 
    (
        CASE bitfield
            WHEN 1 THEN -10
            WHEN 0 THEN 10
        END
    ) as myAlias
FROM mytable

输出

MYALIAS
-------
-1340
6730
-8550
1330
-7780
2340

没有类型转换字段:SQL Fiddle Demo

SELECT
    CASE bitfield
      WHEN 1 THEN numberfield * -10
      WHEN 0 THEN numberfield * 10
    END as myAlias
FROM mytable

错误

数据截断:BIGINT UNSIGNED 值超出 '( db_5b3bb. mytable. numberfield* -(10))' 的范围:SELECT CASE 位域 WHEN 1 THEN 数字域 * -10 WHEN 0 THEN 数字域 * 10 END as myAlias FROM mytable

于 2012-05-07T02:10:54.320 回答
0

尝试使用“cast()”函数:

http://dev.mysql.com/doc/refman/5.1/en/cast-functions.html#function_cast

前任: select * from mytable where myfield=cast(somefield as UNSIGNED INTEGER)

于 2012-05-07T01:59:56.320 回答