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.
PostgreSQL 可以处理的查询的最大长度为 2147483648 个字符(有符号的 4 字节整数;请参阅src/include/lib/stringinfo.h
)。
为避免查询大小,您可以将 IN (1, 2) 替换为 IN(从关注者 ID = ?
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:
"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."
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:
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.