hive中字段为字符串类型,where条件不加引号导致查询出来的数据错误,是什么原因呢?
Hive版本为1.2.2
-- 创建测试表
create table bdpread.tmp_test_cs(
code_type varchar(32)
)
;
-- 插入3条数据
insert into table bdpread.tmp_test_cs select '01' from default.dual;
insert into table bdpread.tmp_test_cs select '1' from default.dual;
insert into table bdpread.tmp_test_cs select '10' from default.dual;
select * from bdpread.tmp_test_cs;
-- 此时表中数据有三条:
01
1
10
-- 加入判断,注意code_type是string类型,但是sql中不写单引号传入int类型
select * from bdpread.tmp_test_cs where code_type=1;
01
1
可以发现,除了查询出了1的这条数据,01的这条也查询出来了。有谁知道为什么吗?
一个字符串和一个数字进行比较,会将字符串自动转换为数字类型,而在转换时,只会取字符串中的数字部分,忽略掉其他字符。所以,'01'被转换为数字1,和数字1进行比较时,符合条件,所以查询结果中包含了'01'和'1'这两条数据。想要精确匹配字符串类型的值,可以这样写:select * from bdpread.tmp_test_cs where code_type='1'; 这样只会查询出值为'1'的那条数据。
这要看你表里字段类型是什么,跟数据写不写单引号没有一毛钱关系
字段类型是int,即使写了单引号,存的还是个int
当然前提是引号里的字符串可以转成int,如果是'abc'这种东西会报错