[英]Multiply an array from a column with the result of a count from another query
[英]Query from a array and count the query result in Postgresql
我有一個keywordsList 表有兩列,像這樣:
id | keywords
-------------
1 | [apple cake, apple pie, apple cookie]
-------------
2 | [banana cake, banana juice]
-------------
3. | [orange candy]
我想查詢與關鍵字列中的任何內容匹配的字符串,並計算我成功搜索的結果數量。
例如,我搜索“apple”,我想得到這樣的結果:
id | keywords | totalCount
-------------------------------------------------
1 | [apple cake, apple pie, apple cookie] | 1
我想得到結果顯示哪個數組匹配“蘋果”,以及我得到了多少行。
這是我嘗試獲得該結果的代碼:
SELECT DISTINCT "id", "keywords", COUNT("id") OVER () as totalCount
FROM (SELECT DISTINCT *, unnest("keywords") AS "unnestKeywords" FROM "keywordsList") AS "keywordsList"
WHERE "unnestKeywords" ILIKE "%apple%"
但我得到這樣的結果:
id | keywords | totalCount
-------------------------------------------------
1 | [apple cake, apple pie, apple cookie] | 3
我可以獲得正確的 id 和關鍵字列,但無法獲得正確的計數。
希望得到任何建議。 謝謝
您可以在標量子選擇中進行計數,從而無需 GROUP BY。 然后您可以過濾該計數,僅獲取關鍵字出現的那些
select id,
keywords,
keyword_count,
sum(keyword_count) over () as totalcount
from (
select kl.id,
kl.keywords,
(select count(distinct word)
from unnest(kl.keywords) as u(word)
where u.word ilike '%apple%') as keyword_count
from keywordlist kl
) t
where keyword_count > 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.