在postgresql中为Varchar和Char数据类型使用“between”运算符

问题描述 投票:0回答:2

我想在表中的“varchar”和“char(5)”列上使用“between”运算符。但是,我没有看到结果中“between”运算符的任何影响。

请注意,“code”是列名

我有一个类型为VARCHAR的列的表,我应用强制转换操作将其转换为“CHAR(5)”类型。当我在任一列的查询中的运算符之间应用时,它不会产生过滤结果。

对于VARCHAR COLUMN

select code from diagnoses where code between '4254' and 
'5855'

对于CHAR(5)COLUMN

 select cast(code as char(5)) as code
 from diagnoses where code between '4254' and '5855' 

我希望输出只有这个范围内的记录,但我得到的记录也不符合这个标准。请在下面找到示例截图

enter image description here

sql postgresql pgadmin pgadmin-4
2个回答
1
投票

demo:db<>fiddle

基于字符的类型的BETWEEN运算符适用于字母顺序。这意味着它使用了订单

4254
45829
486
...
58381
5845
5855

所以输出是完全正确的。

如果需要数字顺序,则必须将其强制转换为适当的数据类型:

select 
    cast(code as char(5)) as code
from 
    diagnoses 
where 
    cast(code as int) between 4254 and 5855 -- cast here

结果:

4254
5119
5589
5845
5855

1
投票

我会写这样的逻辑:

where code::int between 4254 and 5855 

或者,如果要使用索引:

where code between '4254' and '5855' and
      length(code) = 4
© www.soinside.com 2019 - 2024. All rights reserved.