我在选择中有一个别名:
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在执行“myAlias”是签名整数的任何操作之前?
谢谢!
编辑:
我试过
SELECT
CAST(CASE ....
WHEN 1 THEN somefield * -10
WHEN 0 THEN somefield * 10
END AS SIGNED) as myAlias
FROM
....
没有成功!
答案 0 :(得分: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);
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
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
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 numberfield * - 10当0,那么numberfield * 10 END为myAlias from mytable
答案 1 :(得分:0)
尝试使用“cast()”函数:
http://dev.mysql.com/doc/refman/5.1/en/cast-functions.html#function_cast
EX:
select * from mytable where myfield=cast(somefield as UNSIGNED INTEGER)