gpt4 book ai didi

sql - rails union hack,如何将两个不同的查询放在一起

转载 作者:数据小太阳 更新时间:2023-10-29 06:39:30 26 4
gpt4 key购买 nike

我有一个查询,它在同一个表中搜索两个单独的字段...寻找最有可能是特定城市但也可能是国家的位置...即需要两个字段。

表格看起来像:

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 联合的信息...

最佳答案

使用 ActiveRecord 本身不可能执行 UNION 查询。所以有两种解决方案:

  • 使用find_by_sql根据需要构建查询。我不建议这样做。
  • 使用类似 union 的插件执行 UNION sql 查询。

关于sql - rails union hack,如何将两个不同的查询放在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1584589/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com