Rails ActiveRecord : 加入 LEFT JOIN 而不是 INNER JOIN [英] Rails ActiveRecord :joins with LEFT JOIN instead of INNER JOIN

查看:35
本文介绍了Rails ActiveRecord : 加入 LEFT JOIN 而不是 INNER JOIN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码

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?

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

推荐答案

你可以试试这个

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

这篇关于Rails ActiveRecord : 加入 LEFT JOIN 而不是 INNER JOIN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆