MySQL基础知识:关于mysql中string和number的转换问题
mysql中string和number的转换
今天无意中发现一个很奇怪的现象,在写sql语句的时候,想筛选列值为空字符串的记录,结果把列值为0的记录也一起筛选出来了
总结原因如下
当非同类型比较,等号两边分别为number和string之一时候,mysql会把string类型和number类型进行转换:
(1)数值型字符串
如''、'string'、'abc'等,会转换成0
eg:
select ” = 0 from dual; —结果:1
select ‘a’ = 0 from dual; —结果:1
select ‘a’ = 0 from dual; —结果:1
(2)number和string拼接字符串
如'123string'、'0123string'等,会取头部类型进行转换
eg:
select ‘123abc’ = 0 from dual; —结果:0
select ‘123abc’ = 123 from dual; —结果:1
select ‘0123abc’ = 123 from dual; —结果:1
select ‘123abc’ + ’23def’ from dual; —结果:146
select ‘123abc’ = 123 from dual; —结果:1
select ‘0123abc’ = 123 from dual; —结果:1
select ‘123abc’ + ’23def’ from dual; —结果:146
(3)string和number拼接字符串
如'string123'、'string0123'等,会取头部类型进行转换
eg:
select ‘abc123’ = 0 from dual; —结果:1
select ‘abc123’ = 123 from dual; —结果:0
select ‘abc123’ + ‘def45’ from dual; —结果:0
select ‘abc123’ = 123 from dual; —结果:0
select ‘abc123’ + ‘def45’ from dual; —结果:0
(4)数值型字符串则会转换成相应的number
如'123'->123、'023'->23等
eg:
select ‘123’ = 0 from dual; —结果:0
select ‘123’ = 123 from dual; —结果:1
select ‘0123’ = 123 from dual; —结果:1
select ‘123’ = 123 from dual; —结果:1
select ‘0123’ = 123 from dual; —结果:1
(5)number则直接转换成对应的string
eg:
select 123 = ‘123’ from dual; —结果:1
所以针对我遇到的问题,mysql把''当成字符串处理,转换成了0,0=0,所以把列值为0的记录也一并筛选了出来
+号的处理方式同理:
如果+号两边类型不一致,则把string转换成number处理
select ‘0string’ + 0 = ‘string’ from dual; —结果:1 ‘0string’ + 0 -> 0 + 0 = 0,0和’string’进行比较
select ‘string’ = ‘string’ + 0 from dual; —结果:1 ‘string’ + 0 -> 0 + 0 = 0,’string’和0进行比较
select ‘string’ + 0 = ‘string’ + 0 from dual; —结果:1 ‘string’ + 0 -> 0 + 0 ,0和0进行比较
select ‘string’ + 0 = ‘string’ + 1 from dual; —结果:0 ‘string’ + 0 -> 0 + 0 ,’string’ + 1 -> 0 + 1,0和1进行比较
select ‘string’ = ‘string’ + 0 from dual; —结果:1 ‘string’ + 0 -> 0 + 0 = 0,’string’和0进行比较
select ‘string’ + 0 = ‘string’ + 0 from dual; —结果:1 ‘string’ + 0 -> 0 + 0 ,0和0进行比较
select ‘string’ + 0 = ‘string’ + 1 from dual; —结果:0 ‘string’ + 0 -> 0 + 0 ,’string’ + 1 -> 0 + 1,0和1进行比较
参考链接:http://stackoverflow.com/questions/22080382/mysql-why-comparing-a-string-to-0-gives-true
附赠mysql文档说明:https://dev.mysql.com/doc/refman/5.7/en/type-conversion.html
mysql中hex、varchar、number相互转换
hex(‘20’)= 14
select HEX(20) from DUAL – result: 14
select HEX(20) from DUAL – result: 14
然后这串数字就能变为16进制字符串,只需要加上0x的前缀!
- UNHEX(‘14’) – 每对十六进制数字转化为一个字符。
- UNHEX(‘14’),对应 SI, 该字符无法正确输出
但是ORDER BY UNHEX(‘14’) 是可以的。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。