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

时间:2014-05-16 05:05:04

标签: ruby sequel sequel-gem

是否可以使用续集来执行这样的查询:

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

我知道我可以使用续集一次执行这些查询,但我想同时执行所有这些查询。

4 个答案:

答案 0 :(得分:5)

您可以在不使用以下内容编写原始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\""

答案 1 :(得分:4)

是的,你可以用续集宝石做好。

require 'sequel'

DB = Sequel.sqlite # memory database

DB.create_table :users do
  primary_key :id
  String :name
end

users = DB[:users] # Create a dataset
users.insert(:name => 'jim')

DB.create_table :contacts do
  primary_key :id
  String :name
end
contacts = DB[:contacts] # Create a dataset
contacts.insert(:name => 'first')


DB['select (select count(*) from users where name = "jim") as users, 
           (select count(*) from contacts where name = "first") as contacts'].each do |row|
  puts row
end


#{:users=>1, :contacts=>1}

但应该注意的是,在续集方法中包含原始字符串并不是一个好主意。 它们可以如下提取:

DB['select (select count(*) from users where name = ?) as users, 
           (select count(*) from contacts where name = ?) as contacts, 'jim', 'first'].each do |row|
  puts row
end

另外,如另一个答案中所述,您可以完全表达此查询而无需借助SQL,这更符合模块的精神。 :

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

dataset.sql

# SELECT (SELECT count('*') FROM `users` WHERE (`name` = 'jim')) AS 'users', (SELECT count('*') FROM `contacts` WHERE (`name` = 'first')) AS 'contacts'

dataset.first

# {:users=>1, :contacts=>1}

答案 2 :(得分:1)

您可以按照上面的说明执行,查询没有问题。 我已经执行了相同的操作并且执行时没有任何问题..

以下是我执行的内容

     select( SELECT count(*) FROM `abcde` where `User_ID`=4001) as "aa",
     (SELECT count(*) FROM `abcdef` where `User_ID`=4018) as "bbb"

结果:

   aa   bbb
   181  364

答案 3 :(得分:0)

你需要在select之后添加*,可能是一些括号:

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