0

我如何进行一项操作在我执行这样的查询之间: 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))'
4

1 回答 1

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
于 2013-01-24T03:56:21.353 回答