当变量可以取负值时,在无符号数之间进行操作[关闭]
Posted
技术标签:
【中文标题】当变量可以取负值时,在无符号数之间进行操作[关闭]【英文标题】:make operation between to unsigned number when variables can take negative value [closed] 【发布时间】:2013-01-23 20:21:55 【问题描述】:我如何在执行以下查询之间进行一项操作:
types.init 和 types.end 是一个无符号数,在这种情况下 B.init=0 and B.end=0
SET @init:=20;
SET @end:=100;
SELECT
A.`type_id`, B.`type_id`,count(A.id)
FROM
`types` A ,`types` B
WHERE
A.`init` BETWEEN B.`init`- @init
AND B.`init` + @init
AND A.`end` BETWEEN B.`end`- @end
AND B.`end` + @end
那么就会出现这个错误:
#1690 - BIGINT UNSIGNED value is out of range in '(`database`.`B`.`init` - (@init))'
【问题讨论】:
您可能应该提供一个数据样本,并显示您希望使用B.init=0
和/或B.end=0
的行的结果。或者直接告诉我们在@init > types.init
和/或@end > types.end
时应如何计算起始边界。
【参考方案1】:
您要么需要使用CAST 转换为SIGNED,要么使用CASE 来检查B.init >= @init。
对于前一种情况,您的查询将如下所示:
WHERE
CAST(A.`init` AS SIGNED) BETWEEN CAST(B.`init` AS SIGNED) - @init
AND CAST(B.`init` AS SIGNED) + @init
AND CAST(A.`end` AS SIGNED) BETWEEN CAST(B.`end` AS SIGNED) - @end
AND CAST(B.`end` AS SIGNED) + @end
对于后者:
WHERE
A.`init` BETWEEN CASE WHEN B.`init` >= @init THEN B.`init`- @init ELSE 0 END
AND B.`init` + @init
AND A.`end` BETWEEN CASE WHEN B.`end` >= @end THEN B.`end`- @end ELSE 0 END
AND B.`end` + @end
【讨论】:
以上是关于当变量可以取负值时,在无符号数之间进行操作[关闭]的主要内容,如果未能解决你的问题,请参考以下文章