简体   繁体   中英

Query from a array and count the query result in Postgresql

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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