Ruby-on-rails Rails ActiveRecord : 加入 LEFT JOIN 而不是 INNER JOIN

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1509692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:49:43  来源:igfitidea点击:

Rails ActiveRecord :joins with LEFT JOIN instead of INNER JOIN

ruby-on-railsactiverecordjoinleft-joininner-join

提问by Jakub Arnold

I have this code

我有这个代码

User.find(:all, :limit => 10, :joins => :user_points,
                :select => "users.*, count(user_points.id)", :group =>
                "user_points.user_id")

which generates following sql

生成以下sql

SELECT users.*, count(user_points.id) 
FROM `users` 
INNER JOIN `user_points` 
ON user_points.user_id = users.id 
GROUP BY user_points.user_id 
LIMIT 10

is it possible to make LEFT JOIN instead of INNER JOIN other way than User.find_by_sqland manualy typing the query?

除了User.find_by_sql手动输入查询之外,是否可以使用 LEFT JOIN 而不是 INNER JOIN ?

回答by Kylo

You can try this

你可以试试这个

User.find(:all, limit: 10,
            joins:  "LEFT JOIN `user_points` ON user_points.user_id = users.id" ,
            select: "users.*, count(user_points.id)", 
            group:  "user_points.user_id")

回答by 8bithero

Just for future reference, adding :allgives a deprecated message. In later versions of rails you can simply chain the methods like this:

仅供将来参考,添加:all会给出一条已弃用的消息。在更高版本的 rails 中,您可以简单地将方法链接如下:

User.joins("LEFT JOIN `user_points` ON user_points.user_id = users.id").select("users.*, count(user_points.id)").group("user_points.user_id")

OR use a scopelike this:

或者使用这样的范围

scope :my_scope_name_here, -> { 
        joins("LEFT JOIN `user_points` ON user_points.user_id = users.id")
        .select("users.*, count(user_points.id)")
        .group("user_points.user_id")
}

You can also chain .wherebetween the .joinand the .select. Hope this helps someone in the future.

您还可以.where.join和之间进行链接.select。希望这对未来的人有所帮助。

回答by Santhosh

Rails 5 has a left_outer_joinsmethod. So you can do

Rails 5 有一个left_outer_joins方法。所以你可以做

User.left_outer_joins(:user_points)

or use the alias

或使用别名

User.left_joins(:user_points)