【问题标题】:Postgresql Query - Return all matching search terms for each result row when using an ANY query and LIKEPostgresql 查询 - 使用 ANY 查询和 LIKE 时返回每个结果行的所有匹配搜索词
【发布时间】:2023-03-14 07:58:02
【问题描述】:

基本上我想弄清楚的是,在运行使用ANYIN 查找项目列表的查询时,是否有一种方法可以返回除匹配行之外的所有匹配搜索词。在大多数情况下,搜索词将与返回的列值完全匹配,但在文本搜索或具有某些扩展名(如 IP4r)的情况下,情况并非总是如此。此外,您可以在一行中匹配多个搜索词。

为了具体化,假设这是我的查询:

SELECT id, item_name, description FROM items WHERE description LIKE ANY('{%gaming%, %computer%, %socks%, %men%}');

它返回以下两行:

id, item_name, description
1, 'computer', 'super fast gaming computer that will help you win'
5, 'socks', 'These socks are sure to please the men in your family'

我想知道哪些原始搜索词映射到返回的结果行。换句话说,我希望返回的行看起来像这样:

id, search_terms, item_name, description
1, '{%gaming%, %computer%}', 'computer', 'super fast gaming computer that will help you win'
5, '{%socks%, %men%}', 'socks', 'These socks are sure to please the men in your family'

有没有办法在 PostgreSQL 中有效地做到这一点?在上面的示例中,我们使用带字符串的 LIKE,但在我的实际场景中,我使用 IP4r 扩展对 CIDR 范围进行 IP 查找,您可以在同一个返回的 CIDR 范围内拥有多个 IP 地址。

我之前问过这个问题:PostgreSQL 9.5: Return matching search terms in each result row when using LIKE,它使用 CASE 语句几乎解决了我在这里描述的问题。

上述场景中增加的复杂性在于,您可以让多个搜索词匹配单行(例如,gamingcomputer 都与描述 super fast gaming computer that will help you win 匹配)。如果您使用 CASE 语句,则只有 CASE 语句中的第一个匹配项被设置为搜索词,您会错过任何其他匹配的搜索词。

感谢您的帮助!

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    这是一种使用VALUES的方式:

    SELECT i.id, i.item_name, i.description, m.pat
    FROM items AS i
       JOIN (VALUES ('%gaming%'), ('%computer%'), ('%socks%'), ('%men%')) AS m(pat)
          ON i.description LIKE m.pat;
    

    【讨论】:

    • 谢谢!这是每场比赛返回一行,这绝对有效。有没有一种有效的方法将m.pat 字段分组到一个数组(单行)中,或者在应用层中这样做会更有效?
    • 您可以使用array_agg 将一组行转换为一个数组,而unnest 则相反。因此,您选择哪种格式并不重要。
    猜你喜欢
    • 2018-02-12
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 2017-05-24
    • 1970-01-01
    • 2021-08-15
    相关资源
    最近更新 更多