select resultset of counts by array param in postgres

限于喜欢 提交于 2019-12-12 01:25:45

问题


I've been searching for this and it seems like it should be something simple, but apparently not so much. I want to return a resultSet within PostgreSQL 9.4.x using an array parameter so:

| id | count |
--------------
| 1  |   22  |
--------------
| 2  |   14  |
--------------
| 14 |   3   |

where I'm submitting a parameter of {'1','2','14'}.

Using something (clearly not) like:

SELECT id, count(a.*) 
FROM tablename a
WHERE a.id::int IN array('{1,2,14}'::int);

I want to test it first of course, and then write it as a storedProc (function) to make this simple.


回答1:


Forget it, here is the answer:

SELECT a.id,
       COUNT(a.id)
FROM tableName a
WHERE a.id IN
    (SELECT b.id 
     FROM tableName b
     WHERE b.id = ANY('{1,2,14}'::int[])
    )
GROUP BY a.id;



回答2:


You can simplify to:

SELECT id, count(*) AS ct
FROM   tbl
WHERE  id = ANY('{1,2,14}'::int[])
GROUP  BY 1;

More:

  • Check if value exists in Postgres array

To include IDs from the input array that are not found I suggest unnest() followed by a LEFT JOIN:

SELECT id, count(t.id) AS ct
FROM   unnest('{1,2,14}'::int[]) id
LEFT   JOIN tbl t USING (id)
GROUP  BY 1;

Related:

  • Preserve all elements of an array while (left) joining to a table

If there can be NULL values in the array parameter as well as in the id column (which would be an odd design), you'd need (slower!) NULL-safe comparison:

SELECT id, count(t.id) AS ct
FROM   unnest('{1,2,14}'::int[]) id
LEFT   JOIN tbl t ON t.id IS NOT DISTINCT FROM id.id
GROUP  BY 1;


来源:https://stackoverflow.com/questions/34034396/select-resultset-of-counts-by-array-param-in-postgres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!