Maximum length of an SQL Query

自作多情 提交于 2020-01-03 07:18:34

问题


SELECT f.* 
FROM feeds f, 
     user_feeds uf 
WHERE (f.id=uf.feed_id and uf.user_id in (1,2,5,6,23,45)) 
ORDER BY created_at DESC

This is a query used to construct a user's feeds. The issue I have with this query is that the "uf.user_id in ()" increases as the number of users he follows increase.

What is the allowed max length of an SQL query ? Is there a better way to implement my above query ?

Note: I am using ActiveRecord. And I am using Postgres.


回答1:


The maximum length of a query that PostgreSQL can process is 2147483648 characters (signed 4-byte integer; see src/include/lib/stringinfo.h).




回答2:


To avoid the query size, you could replace the IN (1, 2) with IN (select followed_id from following where follower_id = ?) or whatever the appropriate query would be to find the ids of the followed users from the follower's id.




回答3:


While there is no (real) limit on the length of the query string, there is a limit on the number of IN (x,y,z...) clauses: 10000, configurable in the postgres.ini-file:

See: http://grokbase.com/t/postgresql/pgsql-general/061mc7pxg6/what-is-the-maximum-length-of-an-in-a-b-c-d-list-in-postgresql :

"In 7.4 and earlier it depends on the max_expr_depth setting." ... "In 8.0 and later max_expr_depth is gone and the limit depends on max_stack_depth."




回答4:


You could consider using a subquery to construct the IN portion of your original WHERE clause. So the result would look something like this:

"SELECT f.* FROM feeds f, user_feeds uf WHERE (f.id=uf.feed_id and uf.user_id in (SELECT followed where follower = id)) ORDER BY created_at DESC"

Obviously the subquery isn't right as I posted it, but that should give you the general idea.




回答5:


Use a correlated sub-query. If you have a table that holds the users a member follows your query text won't grow.

For example:

SELECT f.* 
FROM feeds f, 
     user_feeds uf 
WHERE f.id=uf.feed_id 
  AND EXISTS (SELECT 'X'
              FROM follows
              WHERE follows.user_id = uf.user_id) 
ORDER BY created_at DESC;


来源:https://stackoverflow.com/questions/4936731/maximum-length-of-an-sql-query

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