Home > Software design >  Query from a array and count the query result in Postgresql
Query from a array and count the query result in Postgresql

Time:07-26

I have a keywordsList table has two columns, like this:

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:

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.
Hope to get any suggestion. Thanks

CodePudding user response:

You can do the counting in a scalar sub-select which removes the need of a 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

  • Related