很简单,正在尝试这样做
SELECT (artist_name || ' ' || name) as full_name FROM "songs" WHERE "songs"."working" = 't' AND (full_name ILIKE('%Jack Beats%')) AND (full_name ILIKE('%Epidemic%')) AND (full_name ILIKE('%Dillon Francis%')) ORDER BY songs.published_at asc LIMIT 1
但我得到
ActiveRecord::StatementInvalid: PG::Error: ERROR: column "full_name" does not exist
我尝试在电台之前添加表名称,但没有效果。
正如 sub_stantial 在注释中提到的,您不能在 WHERE 子句中引用 SELECT 中的别名。您可以按照 dwurf 建议使用派生表,但 Rails 中的派生表有点混乱。您可以在 WHERE 内扩展串联:
Song.where(:working => true)
.where("artist_name || ' ' || name ILIKE ?", '%Jack Beats%')
.where("artist_name || ' ' || name ILIKE ?", '%Epidemic%')
.where("artist_name || ' ' || name ILIKE ?", '%Dillon Francis%')
.order('songs.published_at asc')
.limit(1)
如果你经常做这种事情,命名范围可能会很有用:
class Song < ActiveRecord::Base
#...
def self.full_name_like(name)
where("artist_name || ' ' || name ILIKE ?", "%#{name}%")
end
end
进而:
Song.where(:working => true)
.full_name_like('Jack Beats')
.full_name_like('Epidemic')
.full_name_like('Dillon Francis')
.order('songs.published_at asc')
.limit(1)
如果您的应用程序要进行大量像这样的 ILIKE 搜索,那么您可能需要研究全文搜索系统:LIKE 查询会导致表扫描,而表扫描会导致悲伤。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)