今天有一个之前常发生的sql 错误 BIGINT UNSIGNED value is out of range , 错误常见但一直没百度查.
这个月初出了同样的问题. 记录下 水一下博客.
问题场景 . 查询SQL
表结构
CREATE TABLE `table1` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`tim1` int(11) NOT NULL DEFAULT '0' COMMENT '时间1',
`tim2` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '无符号 时间2',
PRIMARY KEY (`trade_id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8;问题语句
select * from table1 where (time1 - time2) > 10;光看上一条没问题, 但如果 time1 小于 time2 就出了问题了, 原因在于time2 设置了unsigned .
mysql当两个字段想减时,如果其中一个或两个字段的类型的unsigned无签名类型,如果想减的值小于0则会报错(BIGINT UNSIGNED value is out of range)
解决办法:
一、修改字段类型
二、使用cast函数转字段为signed类型
select * from table1 where time1 - cast(time2 as signed)