【问题标题】:how generate LIKE on arrays of values in where clause of sql query with rails?如何在带有rails的sql查询的where子句中的值数组上生成LIKE?
【发布时间】:2015-01-16 01:08:02
【问题描述】:

我有一个值数组:

words = ['foo', 'bar', 'baz']

我想用 LIKE(而不是“IN”)自动生成 where 子句。

我现在做什么:

words = params[:content].split(' ').map { |w| "%#{w.strip}%" }

where = []
words.size.times do
  where << 'name LIKE ?'
end

tags = Tag.where(where.join(' OR '), *words)

生成正确的请求 SQL:

SELECT `tags`.* FROM `tags` WHERE (name LIKE '%foo%' OR name LIKE '%bar%' OR name LIKE '%baz%')

但这不是很好的方式......

当我想将数组值与等号进行比较时,我们可以这样做:

 Tag.where(name: words)

有可能做同样的事情但不生成IN,而是多个OR LIKE "%VALUE%"?怎么样?

【问题讨论】:

    标签: mysql sql arrays ruby-on-rails-4 rails-activerecord


    【解决方案1】:

    在 postgresql 中它是这样工作的:

    Tag.where("name iLIKE ANY ( array[?] )", words)
    

    SQL RLIKE (正则表达式)

    Tag.where("name RLIKE ?", words.join("|"))
    

    SQL select(效率不高):

    Tag.select{ |c| c.name =~ Regexp.new(words.join("|"), true) }
    

    作为 Tag.rb (SQL) 中的范围

    scope :ilike_any, -> (words) {  where("name RLIKE ?", words.join("|")) }
    

    这使您能够做到:

    words = %w(word1 word2 word3)
    Tag.ilike_any(words)
    

    【讨论】:

    • 有解决方案可以同时 RLIKE 多个属性,例如“名称”和“描述”吗?
    • 解决了一个棘手的问题。谢谢!
    猜你喜欢
    • 2017-10-03
    • 2012-06-10
    • 2022-01-06
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-20
    相关资源
    最近更新 更多