当前位置 : 主页 > 编程语言 > ruby >

ruby – 使用续集gem的多个聚合查询

来源:互联网 收集:自由互联 发布时间:2021-06-23
是否可以使用续集来执行这样的查询: select (select count(*) from users where blah = 'blah') as "users", (select count(*) from contacts where blah = 'blah') as "contacts" 我知道我可以使用续集一次执行这些查询
是否可以使用续集来执行这样的查询:

select (select count(*) from users where blah = 'blah') as "users",
       (select count(*) from contacts where blah = 'blah') as "contacts"

我知道我可以使用续集一次执行这些查询,但我想同时执行它们.

您可以在不使用以下内容编写原始SQL的情况下执行该查询:

dataset = DB.select {[ 
  DB[:users].where(blah: 'blah').select { count('*') }.as(:users),
  DB[:contacts].where(blah: 'blah').select { count('*') }.as(:contacts) 
]}

dataset.first
# => { users: X, contacts: Y }

dataset.sql
# => "SELECT (SELECT count('*') FROM \"users\" WHERE (\"blah\" = 'blah')) AS \"users\", 
#            (SELECT count('*') FROM \"contacts\" WHERE (\"blah\" = 'blah')) AS \"contacts\""
网友评论