3

是否可以使用 sequel 执行这样的查询:

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

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

4

4 回答 4

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\""
于 2014-05-21T00:22:12.950 回答
4

是的,您可以使用 sequel gem 做到这一点。

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}

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

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}
于 2014-05-20T13:52:45.130 回答
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
于 2014-05-16T05:13:19.013 回答
0

您需要在 select 之后添加 * from 并且可能是一些括号:

select * from ((select count(*) from users where blah = 'blah') as "users",
   (select count(*) from contacts where blah = 'blah') as "contacts")
于 2014-05-16T05:12:35.393 回答