dpb_4431 2018-10-09 01:12
浏览 81
已采纳

重写大IN子句的最有效方法是什么?

I wrote an API using go and gorm that runs calculations on our database and returns the results.

I just hit the parameter limit for an IN condition when using an aggregate. Example query:

SELECT SUM(total_amount) from Table where user_id in(...70k parameters) group by user_id

One of my current edge cases has > 65535 user ids so my Postgres client is throwing an error:

got 66037 parameters but PostgreSQL only supports 65535 parameters

I'm not sure what the best way to approach this is. One that will handle the large amount of parameters for this edge case while not affecting my typical use case. Do I chunk the ids and iterate through multiple queries storing it in memory until I have all the data I need? Use ANY(VALUES)...

Obviously from the query I have very limited knowledge of Postgres so any help would be incredibly appreciated.

  • 写回答

1条回答 默认 最新

  • dou1908 2018-10-09 01:51
    关注

    You can replace user_id IN (value [, ...]) with one of:

    user_id IN (subquery)
    user_id = ANY (subquery)
    user_id = ANY (array expression)
    

    Neither subqueries nor arrays exhibit the same limitation. The shortest input syntax would be:

    user_id = ANY ('{1,2,3}'::int[])  -- make array type match type of user_id
    

    Details and more options:

    Or you might create a (temporary) table tmp_usr(user_id int), import to it, maybe with SQL COPY or psql \copy instead of INSERT for best performance with very big sets, and then join to the table like:

    SELECT SUM(total_amount)
    FROM   tbl
    JOIN   tmp_usr USING (user_id)
    GROUP  BY user_id;
    

    BTW, GROUP BY user_id without including user_id in the SELECT list looks suspicious. May be a simplified example query.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)