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 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误