Rails ActiveRecord:以LEFT JOIN代替INNER JOIN联接


74

我有这个代码

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

生成以下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

除了User.find_by_sql手动键入查询外,是否可以通过其他方式使LEFT JOIN代替INNER JOIN ?

Answers:


85

你可以试试这个

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")

太好了,这正是我想要的东西
雅库布·阿诺德

可以,但是雅库布对此有何期待?用户没有积分?如果是这样,我认为它需要一个WHERE user_points.user_id IS NULL,不是吗?
2015年

@Kylo是否在rails中有一个构造来创建左联接而无需输入字符串?
BKSpurgeon'2

39

仅供以后参考,添加将: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")

或使用如下范围

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")
}

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


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.