如何将此查询转换为活动记录

时间:2018-06-11 06:27:00

标签: sql ruby-on-rails ruby ruby-on-rails-4 activerecord

我正在尝试将此查询转换为有效记录,但没有任何运气。任何人都可以指导我如何将此查询从原始SQL转换为活动记录查询

select users.* from
    (
    select email from players_schema.inv_emails where inv_emails.created_at <= (current_date - interval '14 days')
    union
    select email from players_schema.blks where blks.created_at <= (current_date - interval '14 days')
    union
    select email from players_schema.bouces where bouces.created_at <= (current_date - interval '14 days')
    ) email
    join football_schema.users on users.email = email.email; 

我正在使用rails 4.2

2 个答案:

答案 0 :(得分:0)

最后,我得到了解决方案

User.from("(#{players_schema.inv_emails.to_sql} UNION # 
{players_schema.bouces.to_sql} UNION #{players_schema.blks.to_sql} ) 
AS invalid_emails").joins("INNER join football_schema.users on 
users.email = invalid_emails.email")

答案 1 :(得分:-1)

您可以使用active_record_union。 您问题的完美解决方案。 here是文档