使用通配符查找bigint列的记录

时间:2014-12-10 17:28:15

标签: ruby-on-rails postgresql

我有一个API,其中包含一个带有UPC-12值的数据库。有时API调用将带有UPC-10代码。我的db upc列为bigint,因此它删除了UPC-12值的前导0。与UPC-10相比,这会将最后一位数作为通配符。

我希望能够根据数据库中的记录检查UPC-10值,看看是否匹配。由于我无法使用LIKE,我该怎么做?

目标是做一些事情:

def self.pull_product(upc)
    upc_string = upc.to_s

    if upc_string.length == 10
        # product = Product.where...  use a wildcard to try and match to existing record
    else
        product = Product.find_by_upc(upc)
    end
end

这个Rails 4和Postgresql。

只是为了澄清:

我可能会使用upc参数进行UPC-10 api调用:7618600002。我的数据库具有等效的UPC-12:76186000023。所以,如果我只是在api调用中查询param,我会得到nil。

我需要一种方法来匹配UPC-10参数与数据库中的UPC-12值。

1 个答案:

答案 0 :(得分:0)

你需要像这样使用SQL:

upc between upc_string::int*10 and upc_string::int*10+9

我不知道如何在Rails中编写代码。