【问题标题】:Search with multiple parameter in postgresql ltree在 postgresql ltree 中使用多个参数搜索
【发布时间】:2017-11-21 08:50:49
【问题描述】:

我计划实现一个使用 ltree 作为多级分类的数据库。但是,当我尝试使用路径 x 或 y 获取条目时遇到了麻烦。

         new_table
+-------+--------+---------+
|  id   |  name  |   path  |
----------------------------
|   1   |    a   |   001   |
|   2   |    b   |   002   |
|   3   |    c   | 001.001 |
|   4   |    d   | 002.001 |
|   5   |    e   |   003   |
----------------------------

通过下表,我想获得一个以 001 或 002 开头的 id。但是我似乎无法获得正确的查询。

预期结果:1,2,3,4
这有效:select id from new_table where path <@ '001' or path <@ '002'
这不会(导致语法错误):select id from ingredient where ingredient_path <@ '001|002'

这让我感到困惑,因为documentation 表示使用 | (或)符号是可以接受的。

我对 ltree 很陌生,希望我能得到一个很容易理解的答案。

【问题讨论】:

    标签: postgresql ltree


    【解决方案1】:

    符号 | (或)在ltxtquery 中是可以接受的,所以使用ltree @ ltxtquery 运算符:

    select id from new_table where path @ '001|002'; -- find labels 001 or 002
    -- or
    select id from new_table where path @ '001*|002*'; -- find labels starting with 001 or 002
    

    【讨论】:

    • 这两个有问题,当有'003.001'路径时,'003.001'仍然会包含在查询结果中
    【解决方案2】:

    尝试:

    select id from new_table where path ~ '001|002.*'
    

    我认为,根据文档,OR 不适用于 <@ 运算符,

    ltree

    | 可以在lquery 中使用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多