如何在rails中执行带辅助查询的postgresql

时间:2017-01-26 10:11:48

标签: ruby-on-rails postgresql

我有这个问题:

WITH words_not AS (
        SELECT keywords.id 
        FROM keywords
        WHERE keywords.keyword = any(array['writing'])
    ),
    actes_not AS (
        SELECT actes_keywords.acte_id
        FROM actes_keywords
        WHERE actes_keywords.keyword_id IN (SELECT id FROM words_not)
    )
    SELECT actes.id, actes.acte_date
    FROM actes
    WHERE actes.id NOT IN (SELECT acte_id FROM actes_not);

我想把它“翻译”成rails。但是,文档在其方法中没有.with

http://guides.rubyonrails.org/active_record_querying.html

即这些Rails方法可用:.select.from.where,所以我可以做(例如和简化):

Acte.select("actes.id, actes.date_acte").where("actes.id = ?",5)

但是如何编写此处引用的WITH辅助查询: https://www.postgresql.org/docs/current/static/queries-with.html

1 个答案:

答案 0 :(得分:0)

如果这可能有所帮助:

ids_pas_mots = find_by_sql("SELECT \"motclefs\".\"id\" 
     FROM \"motclefs\" 
     WHERE \"motclefs\".\"motcle\" = any(array[#{pas_mes_mots}])"
     )

ids = ids_pas_mots.map{|l| l.id}

ids_pas_actes = find_by_sql("SELECT \"actes_motclefs\".\"acte_id\"
     FROM \"actes_motclefs\"
     WHERE \"actes_motclefs\".\"motclef_id\" = any(array[#{ids}])")

ids_actes = ids_pas_actes.map { |e| e.acte_id  }.join(",")

self.where("\"actes\".\"id\" NOT IN (#{ids_actes})")