如何在 PostgreSQL 中匹配超字符串?
我有一列单词,其元素如下所示:
id | word
---+---------
1 | cute
2 | advanced
3 | unusual
假设我想运行单词“cuter”或“cutest”的查询。我想做类似的事情:
SELECT * FROM words WHERE word% LIKE 'cutest'
当然,我意识到这不是有效的 SQL 语法,但我想匹配超字符串,而不是子字符串。
我不想使用相似性包,因为它会匹配“notcute”之类的内容,而我只想指定通配符应该位于字段的末尾。
这可以在 Postgres 中实现吗?
I have a column of words whose elements look like this:
id | word
---+---------
1 | cute
2 | advanced
3 | unusual
Suppose I want to run a query for the words "cuter" or "cutest." I'd like to do something like:
SELECT * FROM words WHERE word% LIKE 'cutest'
Of course, I realize that's not valid SQL syntax, but I want to match a superstring, not a substring.
I don't want to use the similarity package because it will match things like "notcute", whereas I only want to specify that the wildcard should go at the end of the field.
Is this possible to achieve in Postgres?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该模式位于
LIKE
的右侧。所以:我添加了另一个
WHERE
条件来消除“cut”或“c”等单词的误报。此外,这可以(并且通常会)仍然使用索引,而表达式'cutest' LIKE word || '%'
绝对不能。请注意,“更可爱”并不符合条件。你的问题有点不一致。
请参阅:
处理单词中的特殊字符作为非特殊的,你必须相应地逃跑。请参阅:
The pattern goes to the right of
LIKE
. So:I added another
WHERE
condition to eliminate false positives on words like 'cut' or just 'c'. Also, this can (and typically will) still use an index, while the expression'cutest' LIKE word || '%'
absolutely cannot.Note that 'cuter' doesn't qualify. Your question is a bit inconsistent there.
See:
To treat special characters in your words as non-special, you'll have to escape accordingly. See: