如何在 PostgreSQL 中匹配超字符串?

发布于 2025-01-11 01:25:26 字数 365 浏览 2 评论 0原文

我有一列单词,其元素如下所示:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅沫记忆 2025-01-18 01:25:26

该模式位于 LIKE 的右侧。所以:

SELECT * FROM words
WHERE 'cutest' LIKE word || '%'
AND    word Like 'cute%';

我添加了另一个 WHERE 条件来消除“cut”或“c”等单词的误报。此外,这可以(并且通常会)仍然使用索引,而表达式 'cutest' LIKE word || '%' 绝对不能。

请注意,“更可爱”并不符合条件。你的问题有点不一致。

请参阅:

处理单词中的特殊字符作为非特殊的,你必须相应地逃跑。请参阅:

The pattern goes to the right of LIKE. So:

SELECT * FROM words
WHERE 'cutest' LIKE word || '%'
AND    word Like 'cute%';

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:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文