简体   繁体   English

rails 5 左外连接

[英]rails 5 left outer join

Need Clarification about left outer joins.需要澄清左外连接。 I have a model named CLub我有一个名为 CLub 的模型

class Club < ApplicationRecord
  has_many :club_members, dependent: :destroy
end

another model named ClubMember另一个名为 ClubMember 的模型

class ClubMember < ApplicationRecord
  belongs_to :club
end

When I run a query like当我运行类似的查询时

Club.left_outer_joins(:club_members)

it gives me all record from lett table它给了我 lett 表中的所有记录

But with something like但是有类似的东西

Club.left_outer_joins(:club_members).where('club_members.is_assigned =?',true)

Its returning only those entries which exist in ClubMember, I was expecting it to return entries from left table which don't exist in ClubMember & existing entries in ClubMember with status TRUE too.它仅返回 ClubMember 中存在的那些条目,我期望它返回左表中 ClubMember 中不存在的条目以及 ClubMember 中状态为 TRUE 的现有条目。 Just leave those entries which exist in ClubMemebr with status FALSE.只需将 ClubMemebr 中存在的条目保留为 FALSE。

I have a wrong concept or doing something wrong?我有一个错误的概念或做错了什么?

LEFT JOIN:左连接:

The LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. LEFT JOIN返回左表中的所有行,即使右表中没有匹配项。

This means that if the ON clause matches 0 (zero) records in the right table;这意味着如果 ON 子句匹配右表中的 0(零)条记录; the join will still return a row in the result, but with NULL in each column from the right table.连接仍将在结果中返回一行,但右表中的每一列都为 NULL。

So if we apply the condition on any column in right table.因此,如果我们将条件应用于右表中的任何列。 Then it will returns the results according to the condition.然后它会根据条件返回结果。 If we want the records where there is notmatch.如果我们想要不匹配的记录。 Than we should add a condition where right table has null values also.比我们应该添加一个条件,其中右表也有空值。 That's what i have added in the code.这就是我在代码中添加的内容。

Club.left_outer_joins(:club_members)
    .where("club_members.is_assigned =true OR club_members.is_assigned is null")

For return the left side plus the coincidences you could add an OR .为了返回左侧加上巧合,您可以添加一个OR something like this:是这样的:

Club.left_outer_joins(:club_members).where('club_members.is_assigned =?',true).or(where('condition with the left side'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM