MySQL字符串列与整数比较


一、问题说明

为了简便在存储时我们经常将整型字段也以字符串形式存储(如id值),但在筛选比较时就需要将该字段转为数值类型。

 

二、处理办法

2.1 使用cast函数进行类型转换

cast函数格式----cast(column_name as target_value_type),例如现有edb_id字段将其转为整型:cast(edb_id as SIGNED)

cast函数支持类型---- 二进制(BINARY)、字符型(CHAR())、日期 (DATE)、时间(TIME)、日期时间型(DATETIME)、浮点数(DECIMAL) 、整型(SIGNED)、无符号整数(UNSIGNED)

整句形如----select * from edb_records where cast(edb_id as SIGNED) > 40000;

 

2.2 使用convert函数进行类型转换

convert和cast功能和用法是一样的,只是参数格式不一样。

convert函数格式----convert(column_name, target_value_type),例如现有edb_id字段将其转为整型:convert(edb_id, SIGNED)

整句形如----select * from edb_records where convert(edb_id, SIGNED) > 40000;

 

三、字符串比较形式说明

整型筛选----select * from edb_records where cast(edb_id as SIGNED) > 40000;----此条语句返回所有edb_id作为数值时大于40000的记录。

字符型筛选----select * from edb_records where edb_id > '40000';----此条语句返回所有edb_id作为数值时大于40000的记录外,因为是字符串比较所以edb_id为999等的记录也将会返回。

 

参考:

http://www.cnblogs.com/xiaoleiel/p/8316508.html

https://www.cnblogs.com/emanlee/p/5998683.html


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM