常用表达式是在不同的关系型数据库(如PostgreSQL,MySQL,Oracle,SQLite3等)中进行相同计算多次运算或出于其他目的而进行的常见实践。
我发现旧宝石postgres_ext具有此功能。 但它未得到维护。 而且它是Postgres特定的
有一些旧问题涉及特定的Rails版本或特定的关系型数据库或涉及Arel
是否有可能以一种常见的方式在Rails中使用WITH
子句?
常用表达式是在不同的关系型数据库(如PostgreSQL,MySQL,Oracle,SQLite3等)中进行相同计算多次运算或出于其他目的而进行的常见实践。
我发现旧宝石postgres_ext具有此功能。 但它未得到维护。 而且它是Postgres特定的
有一些旧问题涉及特定的Rails版本或特定的关系型数据库或涉及Arel
是否有可能以一种常见的方式在Rails中使用WITH
子句?
with
方法ActiveRecord::Relation
。Post.with(posts_with_tags: Post.where("tags_count > ?", 0))
# WITH posts_with_tags AS (
# SELECT * FROM posts WHERE (tags_count > 0)
# )
# SELECT * FROM posts
FROM
值或JOIN
来引用它。Post.with(posts_with_tags: Post.where("tags_count > ?", 0)).from("posts_with_tags AS posts")
# WITH posts_with_tags AS (
# SELECT * FROM posts WHERE (tags_count > 0)
# )
# SELECT * FROM posts_with_tags AS posts
Post.with(posts_with_tags: Post.where("tags_count > ?", 0)).joins("JOIN posts_with_tags ON posts_with_tags.id = posts.id")
# WITH posts_with_tags AS (
# SELECT * FROM posts WHERE (tags_count > 0)
# )
# SELECT * FROM posts JOIN posts_with_tags ON posts_with_tags.id = posts.id
Arel
传递不仅是 AR,而且是 SQL 字面值。Post.with(popular_posts: Arel.sql("... complex sql to calculate posts popularity ..."))
Post.with(
posts_with_comments: Post.where("comments_count > ?", 0),
posts_with_tags: Post.where("tags_count > ?", 0)
)
.with
。Post
.with(posts_with_comments: Post.where("comments_count > ?", 0))
.with(posts_with_tags: Post.where("tags_count > ?", 0))