【问题标题】:Rails includes query with conditions not returning all results from left tableRails 包含条件不返回左表所有结果的查询
【发布时间】:2014-08-28 14:05:51
【问题描述】:

我有两张桌子,帖子和图片。这是 schema.rb 中的相关部分:

create_table "posts", force: true do |t|
  t.string   "name"
  t.string   "body"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "images", force: true do |t|
  t.integer  "post_id"
  t.string   "service_name"
  t.string   "service_url"
  t.datetime "created_at"
  t.datetime "updated_at"
end

我想找到所有帖子并将其与图像表连接起来,并在图像上添加 where 子句。我仍然希望所有帖子都返回,即使它们没有与 where 子句匹配的图像。

我仍然希望此查询返回所有帖子,即使没有服务名称为“acme”的图像:

Post.includes(:images).where("images.service_name" => "acme")

根据rails guide on querying

如果在包含查询的情况下,没有任何帖子的 cmets,则仍会加载所有帖子。通过使用连接(INNER JOIN),连接条件必须匹配,否则不会返回任何记录。

但这不是我看到的行为。在没有图像的情况下,我的查询没有得到任何结果包。

我很欣赏任何想法。

【问题讨论】:

    标签: sql ruby-on-rails postgresql activerecord


    【解决方案1】:

    如果您在LEFT JOIN 之后的 表的列上添加WHERE 条件,则强制它像INNER JOIN 一样工作。

    解决方案

    将表达式拉到LEFT JOIN的条件中。
    根据the manual page you quoted yourself

    推荐的方法是使用连接。

    还有:

    这将生成一个包含 LEFT OUTER JOIN 的查询,而 joins 方法将使用 INNER JOIN 函数生成一个。

    你可能看错了那句话。

    这个应该做你想做的:

    Post.joins('LEFT OUTER JOIN images ON images.post_id = posts.id
                                      AND images.service_name = $$acme$$')
    

    我不是 Ruby 专家,但我得到了这个 from the manual here
    不知道如何转义单引号,所以我改用美元报价。

    【讨论】:

    • 但是在这种情况下,条件在右表上。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多