一, 问题说明
为了简便在存储时我们经常将整型字段也以字符串形式存储 (如 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
来源: http://www.bubuko.com/infodetail-2855540.html