Postgres - 关于值是否包含特定字符串的 WHERE 子句

Postgres - WHERE clause on whether values contain a certain string

如果我想检索所有条目,使得列 foo 的值包含字符串 'bar',在 SQL 或 Postgresql 中是否有简单的方法可以做到这一点?

类似于 ' WHERE foo = "bar"' 但不是 = 而是类似于 ' WHERE foo CONTAINS "bar"'.

Postgres 版本 9.3

使用SQL LIKE语句。这样,您就可以使用 % 作为通配符。因此,您的 WHERE 语句可能类似于:

WHERE foo LIKE '%bar%'

其中之一:

  1. WHERE foo LIKE '%bar%'

  2. WHERE foo ILIKE '%bar%' --case insensitive

  3. WHERE foo ~* 'bar' --regex

  4. WHERE foo ~* '\ybar\y' --matches bar but not foobar (\y is word boundary)

  5. WHERE foo::tsvector @@ 'bar'::tsquery --matches bar but not foobar

您可以索引 foo 以加快 LIKEILIKEregexp 的搜索速度:http://www.postgresql.org/docs/9.3/static/pgtrgm.html#AEN154464 或者在全文列上使用 GIN 或 GIST 索引