Rails 5复杂连接查询

时间:2017-02-22 14:20:56

标签: sql ruby-on-rails postgresql ruby-on-rails-5

我有一个有效的联接查询:

目标是通过campaign_addings检索与idArray)中ID不相关的候选人

Candidate.joins("LEFT OUTER JOIN campaign_addings ON campaign_addings.candidate_id = candidates.id AND campaign_addings.campaign_id IN (#{id.join(',')})").where('campaign_addings.candidate_id IS NULL')

但是很好..这个查询非常难看,我想用纯ActiveRecord DSL重新创建这种行为而没有SQL,我现在有这个:

Candidate.left_outer_joins(:campaign_addings).where(campaign_addings: { campaign_id: id, candidate_id: nil })

好的查询生成:

SELECT COUNT(*) FROM "candidates" LEFT OUTER JOIN campaign_addings ON campaign_addings.candidate_id = candidates.id AND campaign_addings.campaign_id IN (4) WHERE (campaign_addings.candidate_id IS NULL)

糟糕的一个:

SELECT COUNT(DISTINCT "candidates"."id") FROM "candidates" LEFT OUTER JOIN "campaign_addings" ON "campaign_addings"."candidate_id" = "candidates"."id" WHERE "campaign_addings"."campaign_id" = 4 AND "campaign_addings"."candidate_id" IS NULL

你可以看到它非常接近,但我认为我遗漏了一些东西,无法找到加入第一个查询的方法。

编辑:

另外,还有一个SQL注入漏洞

0 个答案:

没有答案