【发布时间】: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.)
-----------------------------
问题是:我怎样才能得到一个由 matching 和 matched 词/线索对分组的相似匹配表?我希望是这样的:
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