简体   繁体   English

从数组中查询并统计Postgresql中的查询结果

[英]Query from a array and count the query result in Postgresql

I have a keywordsList table has two columns, like this:我有一个keywordsList 表有两列,像这样:

id | keywords 
-------------
1  | [apple cake, apple pie, apple cookie]
-------------
2  | [banana cake, banana juice]
-------------
3. | [orange candy]

I want to query the string which match anything in keywords columns and count how many result that I search successfully.我想查询与关键字列中的任何内容匹配的字符串,并计算我成功搜索的结果数量。
For example, I search "apple", and I want to get the result like this:例如,我搜索“apple”,我想得到这样的结果:

id | keywords                              | totalCount
-------------------------------------------------
1  | [apple cake, apple pie, apple cookie] |  1

I want to get the result shows that which array match "apple", and how many rows I got.我想得到结果显示哪个数组匹配“苹果”,以及我得到了多少行。
This's code that I try to get that result:这是我尝试获得该结果的代码:

SELECT DISTINCT "id", "keywords", COUNT("id") OVER () as totalCount 
FROM (SELECT DISTINCT *, unnest("keywords") AS "unnestKeywords" FROM "keywordsList") AS "keywordsList" 
WHERE "unnestKeywords" ILIKE "%apple%"

But I get the result like this:但我得到这样的结果:

id | keywords                              | totalCount
-------------------------------------------------
1  | [apple cake, apple pie, apple cookie] |  3

I could get correct id and keywords columns, but couldn't get correct count.我可以获得正确的 id 和关键字列,但无法获得正确的计数。
Hope to get any suggestion.希望得到任何建议。 Thanks谢谢

You can do the counting in a scalar sub-select which removes the need of a GROUP BY.您可以在标量子选择中进行计数,从而无需 GROUP BY。 Then you can filter on that count, to get only those where the keyword occurs然后您可以过滤该计数,仅获取关键字出现的那些

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

Online example 在线示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM