SQL 查询的最大长度
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
这是用于构建用户提要的查询。我对此查询遇到的问题是“uf.user_id in ()”随着用户关注的用户数量的增加而增加。
SQL 查询允许的最大长度是多少?有没有更好的方法来实现上述查询?
注意:我使用的是 ActiveRecord 和 Postgres。
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 the user follows increases.
What is the allowed max length of an SQL query? Is there a better way to implement the above query?
Note: I am using ActiveRecord and Postgres.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
PostgreSQL 可以处理的查询的最大长度为 2147483648 个字符(带符号的 4 字节整数;请参阅 src/include/lib/stringinfo.h)。
The maximum length of a query that PostgreSQL can process is 2147483648 characters (signed 4-byte integer; see
src/include/lib/stringinfo.h
).虽然查询字符串的长度没有(实际)限制,但 IN (x,y,z...) 子句的数量有限制:10000,可在 postgres.ini 文件中配置:
请参阅:
http://grokbase.com/t/postgresql/pgsql-general/061mc7pxg6/what-is-the-maximum-length-of-an-in-abcd-list-in-postgresql:
“在 7.4 及更早版本中,它取决于 max_expr_depth 设置。”
...
“在 8.0 及更高版本中,max_expr_depth 消失了,限制取决于
最大堆栈深度。”
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."
为了避免查询过大,您可以将 IN (1, 2) 替换为 IN(从关注者中选择 follower_id,其中 follower_id = ?)或任何适当的查询,以从关注者的 id 中查找关注用户的 id。
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.
您可以考虑使用子查询来构造原始 WHERE 子句的 IN 部分。所以结果看起来像这样:
“SELECT f.* FROM feeds f, user_feeds uf WHERE (f.id=uf.feed_id and uf.user_id in (SELECT 随后其中 follower = id)) ORDER BYcreated_at DESC”
显然子查询不像我发布的那样正确,但这应该给您一个总体思路。
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.
使用相关子查询。如果您有一个包含成员关注的用户的表,您的查询文本将不会增长。
例如:
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: