Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple aggregate queries using the sequel gem

Is it possible to use sequel to execute a query like this:

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

I know I can execute these queries one a time using sequel, but I would like to execute them all at the same time.

like image 976
dagda1 Avatar asked May 10 '26 01:05

dagda1


1 Answers

You can do that query without writing raw SQL with the following:

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\""
like image 62
hjing Avatar answered May 11 '26 20:05

hjing