简体   繁体   English

SQL和SQLite:如何搜索以数字开头的字段

[英]SQL and SQLite: how to search field starting with a number

I have a SQL model in which I want to search all words starting with a number. 我有一个SQL模型,我想在其中搜索以数字开头的所有单词。 I can't use regexp since is not supported in SQLite, how can i trick it to have the same results? 我不能使用regexp,因为SQLite不支持它,我如何欺骗它获得相同的结果?

you can do this hack: 您可以这样做:

@results = YourModel.where("(your_field + 0) > 0")

It will return all objects from YourModel with your_field started with number that is more than zero (and not a zero) 它将返回YourModel所有对象,其中your_field以大于零(而不是零)的数字your_field

Or little more native solution: 或更简单的本地解决方案:

@results = YourModel.where("substr(your_field,1,1) IN (?)", (0..9).to_a)

It means that first character of your_field should be one of this numbers : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 这意味着your_field的第一个字符应为以下数字之一 :0、1、2、3、4、5、6、7、8、9

您可以在sqlite中使用glob

Model.filter("field glob ?", '[0-9]*')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM