【问题标题】:Complex query with JSON array in PostgreSQLPostgreSQL 中 JSON 数组的复杂查询
【发布时间】:2021-04-22 00:35:20
【问题描述】:

我的 Postgres DB 中有一个视图,其中包含用于拼图和拼图 ID 的单词/线索对,称为“allwords”:

    word  |  clue       |  puz_id
    =============================
    dog   |  animal     |  1
    -----------------------------
    cat   |  animal     |  1
    -----------------------------
    apple |  fruit      |  2
    -----------------------------
    etc...

现在我想查看数据库中与 JSON 字符串中传递的单词/线索对数组的匹配,这可能看起来像

[{"word": "dog", "clue": "%animal%"}, {"word": "cat", "clue": "%ani%"}, {"word": "appl%", "clue": "fruit"}]

我在 PostgreSQL 中使用jsonb_to_recordset 将 JSON 转换为表,然后我的最终查询如下所示:

select a."word", a."clue", count(a.puz_id) as "matched"
from allwords a
where exists (
    select 1 from 
    jsonb_to_recordset('[{"word": "dog", "clue": "%animal%"}, {"word": "cat", "clue": "%ani%"}, {"word": "appl%", "clue": "fruit"}]'::jsonb) 
    as jsdata("word" text, clue text)
    where a."word" ilike jsdata."word" and a."clue" ilike jsdata.clue
    )
group by a."word", a."clue"
order by "matched" desc;

我现在得到的结果是按数据库表中的匹配单词/线索分组的:

    word  |  clue       |  matched
    =============================
    dog   |  animal     |  5 (e.g.)
    -----------------------------
    cat   |  animal     |  3 (e.g.)
    -----------------------------
    apple |  fruit      |  1 (e.g.)
    -----------------------------

问题是:我怎样才能得到一个由 ma​​tchingma​​tched 词/线索对分组的相似匹配表?我希望是这样的:

    matched_word  |  matched_clue      | matching_word  |  matching_clue       |  matched
    =======================================================================================
    dog           |  %animal%          | dog            |  animal              |  5
    ---------------------------------------------------------------------------------------
    cat           |  %ani%             | cat            |  animal              |  3
    ---------------------------------------------------------------------------------------
    appl%         |  fruit             | apple          |  fruit               |  1
    ---------------------------------------------------------------------------------------

【问题讨论】:

    标签: sql json postgresql


    【解决方案1】:

    明白了!查询应在ilike 上使用join

    select jsdata."word", jsdata.clue, count(a.puz_id) as "matched" from 
    allwords a
    join 
        jsonb_to_recordset('[{"word": "dog", "clue": "%animal%"}, {"word": "cat", "clue": "%ani%"}, {"word": "appl%", "clue": "fruit"}]'::jsonb) 
        as jsdata("word" text, clue text)
        on (a."word" ilike jsdata."word" and a.clue ilike jsdata.clue) -- THIS WORKS!!!
    group by jsdata."word", jsdata.clue
    order by "matched" desc;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 2017-12-06
      • 2016-05-11
      相关资源
      最近更新 更多