【问题标题】:Rails SQL: How to search on a column in a table ignoring all special charactersRails SQL:如何在忽略所有特殊字符的表中搜索列
【发布时间】:2018-09-21 16:29:25
【问题描述】:

我正在 MyTable 中搜索匹配值。

name to search for -> This-is-a (test/with/time)
The name from DB table -> "this-is-a-test-with/time"

如果我可以同时获得列值和搜索值以匹配这样的内容 -> "thisisatestwithtime" 忽略所有特殊字符和空格。

value = This-is-a (test/with/time)
MyTable.where("upper(name) = upper(?)",value.to_s.scan(/[0-9a-z]/i).join("")).first

这会将值转换为删除所有特殊字符的形式,但如何在表中的值上运行相同的值?

【问题讨论】:

  • 您是否期望搜索a-b 会找到ab-cd,因为没有- 它会搜索ab 并匹配abcd?还是应该 a-b 只找到像 a-b-cd 这样的字符串?

标签: sql ruby-on-rails ruby regex postgresql


【解决方案1】:

您可以使用正则表达式搜索。

select * from "table" where "name" ~ 'this' and name ~ 'is' and name ~ 'a' 
and name ~ 'test' and name ~ 'with' and name ~ 'time';

如果您只想搜索整个单词(例如查找 -a- 而不是 cat

name ~ '\ma\M'

如果不区分大小写,请使用

name ~* 'a'

https://www.postgresql.org/docs/9.6/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP

您也可以使用replace 来匹配整个值

select * from table where regex_replace(name, '\W', '') = :name

Table.where("regex_replace(name, '\W', '') = :name", name: 'thisisatestwithtime')

【讨论】:

    猜你喜欢
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多