根据列中整数的第一个数字选择行

时间:2018-03-22 10:28:14

标签: sql postgresql

在PostgreSQL中使用SQL我需要从我的表中选择所有名为" crop"的行。当列#34; field_id"中的整数的第一个数字时是7。

select *
from crop
where (left (field_id,1) = 7)

2 个答案:

答案 0 :(得分:1)

首先,您知道该列是一个数字,所以无论您做什么,我都倾向于明确地转换它:

where left(crop::text, 1) = '7'
where crop::text like '7%'

转换为text只是为了明确发生的事情,并使Postgres更容易解析查询。

更重要的是,如果值具有固定的位数,那么我建议使用数值范围;像这样的东西:

where crop >= 700000 and crop < 800000

这使得Postgres更容易在列上使用索引。

答案 1 :(得分:0)

尝试使用强制转换,如下所示:

select *
from crop
where cast(substring(cast(field_id as varchar(5)),1,1) as int) = 7

其中5在varchar(5)中你应该把数字放在你的整数有多长。