使用 Arel (Rails 5) 构建三联查询

Build triple UNION query using Arel (Rails 5)

user has_many tasks

我正在尝试创建一个 3 select 联合:

Task.from("(#{select1.to_sql} UNION #{select2.to_sql} UNION #{select3.to_sql}) AS tasks")

但是和 Arel 在一起。

我可以轻松地使用 Arel 进行 2 selects 的 UNION 查询:

tasks_t = Task.arel_table
select1 = tasks_t.project('id').where(tasks_t[:id].eq(1)) # SELECT id FROM tasks WHERE tasks.id = 1
select2 = Task.joins(:user).select(:id).where(users: {id: 15}).arel  # SELECT "tasks".id FROM "tasks" INNER JOIN "users" ON "users"."id" = "tasks"."user_id" WHERE "users"."id" = 15
union = select1.union(select2) # SELECT * FROM users WHERE users.id = 1 UNION SELECT * FROM users WHERE users.id = 2

union_with_table_alias = tasks_t.create_table_alias(union, tasks_t.name)
Task.from(union_with_table_alias)
# SELECT "tasks".* FROM ( SELECT id FROM "tasks" WHERE "tasks"."id" = 1 UNION SELECT "tasks"."id" FROM "tasks" INNER JOIN "users" ON "users"."id" = "tasks"."user_id" WHERE "users"."id" =  ) "tasks"  [["id", 15]]

#=> Task::ActiveRecord_Relation [#<Task: id: 1>, #<Task: id: 2>]

如何使用三重联合 select?

select3 = tasks_t.project('id').where(tasks_t[:id].eq(3)) # SELECT id FROM tasks WHERE tasks.id = 3

类似于:

triple_union = select1.union(select2).union(select3)
triple_union_with_table_alias = tasks_t.create_table_alias(triple_union, tasks_t.name)
Task.from(triple_union_with_table_alias)

应该大致翻译成

Task.from("(#{select1.to_sql} UNION #{select2.to_sql} UNION #{select3.to_sql}) AS tasks")

注意上面一行也失败了: Caused by PG::ProtocolViolation: ERROR: bind message supplies 0 parameters, but prepared statement "" requires 1

总结一下: 如何使用 Arel 构建三重 UNION 查询? select 1 UNION select 2 UNION select 3

谢谢

Ruby 2.5.3 Rails 5.2.4 Arel 9.0.0

您不能在 Arel::Nodes::Union 中调用 union,因为在方法定义中会调用两个对象的 astunion 操作的结果不响应 ast:

def union operation, other = nil
  if other
    node_class = Nodes.const_get("Union#{operation.to_s.capitalize}")
  else
    other = operation
    node_class = Nodes::Union
  end

  node_class.new self.ast, other.ast
end

您可以手动调用 Arel::Nodes::Union,将联合的结果作为这些参数中的任何一个传递:

Arel::Nodes::Union.new(Arel::Nodes::Union.new(select1, select2), select3)