2009-10-18 89 views
13

我有一個查詢,它在同一個表中搜索兩個單獨的字段...查找最有可能是特定城市的位置,但也可能是一個國家...即需要兩個領域。rails union hack,如何將兩個不同的查詢結合在一起

表的樣子:

Country City 

Germany Aachen 
USA  Amarillo 
USA  Austin 

結果:

Keyword Sideinfo 

Aachen Germany 
USA  Country 
Austin USA 
Germany Country 

基本上我不知道是否有這樣做,因爲我必須使用兩個單獨的查詢,然後將它們添加了更簡潔的方式(它工作正常):

def self.ajax(search) 
    countries = Location.find(:all, :select=> 'country AS keyword, "Country" AS sideinfo', :joins => :hotels, :conditions => [ 'hotels.email IS NOT NULL AND country LIKE ?', "#{search}%" ], :group => :country) 
    cities = Location.find(:all, :select=> 'city AS keyword, country AS sideinfo', :joins => :hotels, :conditions => [ 'hotels.email IS NOT NULL AND city LIKE ?', "#{search}%" ], :group => :city) 
    out = cities + countries 
    out = out.sort { |a,b| a.keyword <=> b.keyword } 
    out.first(8) 
    end 

我找不到任何有關如何工會使用ActiveRecord ...

+1

此問題dis在ActiveRecord中使用或僞造聯盟的方法:http://stackoverflow.com/questions/6686920/activerecord-query-union – 2014-08-05 02:17:20

回答

7

使用ActiveRecord執行UNION查詢本身不是可能的。因此有兩種解決方案:

  • 使用find_by_sql可以根據需要構建您的查詢。我不會爲此提供建議。
  • 使用像union這樣的插件來執行UNION sql查詢。
+4

現在聯盟已經3歲了。任何人都有更新的解決方案 – 2012-04-19 22:24:37

+0

@BillLeeper雖然你的評論發佈在'12,檢查我的答案,以防萬一你仍在尋找它 – 2015-06-26 07:45:05

+0

@BillLeeper https://github.com/brianhempel/active_record_union是一個更好的寶石。在沒有醜陋的情況下使用ActiveRecord範圍上的聯合。 – lingceng 2015-10-09 02:35:09

2

使用UNION插件,它現在的作品精美的感謝:

def self.ajax3(search) 
    Location.union([{ :select => 'city AS keyword, country AS sideinfo', 
         :joins => :hotels, 
         :conditions => [ 'email IS NOT NULL AND city LIKE ?', "#{search}%" ]}, 
        { :select => 'country AS keyword, "Country" AS sideinfo', 
         :joins => :hotels, 
         :conditions => [ 'email IS NOT NULL AND country LIKE ?', "#{search}%" ]}]) 
    end 
3

我發現一個整潔的黑客使用選擇。 例如,如果您想在User和OtherUser之間建立聯合。

User.select('id from other_users union select id') 

這就會產生此SQL

"SELECT id from other_users union select id FROM users " 

如果有符合條件範圍可以使用的ActiveRecord ::關係where_values方法

condition = OtherUser.example_condtion_scope.where_values.join(' ') 
User.select("id from other_users where #{contition}") 
1

這是現在可以在軌道4,5 ,

locations = Location.arel_table 
hotels = Hotel.arel_table 

countries = Location 
       .select(locations[:country].as("keyword")) 
       .joins(:hotels) 
       .where(hotels[:email].not_eq(nil)) 
       .where(locations[:country].matches("#{search}%")) 

cities = Location 
      .select(locations[:city].as("keyword")) 
      .joins(:hotels) 
      .where(hotels[:email].not_eq(nil)) 
      .where(locations[:city].matches("#{search}%")) 

union = countries.union(cities) 

result = Location.from(locations.create_table_alias(union, :locations).to_sql) 
相關問題