LoginSignup
82
62

More than 5 years have passed since last update.

LEFT OUTER JOINする

Last updated at Posted at 2013-03-12

関連するBのレコードが存在しないAを抽出する

SQL的には

SELECT A.*
FROM A LEFT OUTER JOIN B 
       ON A.id = B.id
WHERE B.id is NULL

これを、Railsでやるには

Rails5以降

A.left_joins(:b).where(b: { id: nil })

Rails4まで(ただし「includesはLEFT JOINのためのメソッドではなくeager loadingのためのものなので、余計なActiveRecord::Baseインスタンスを生成してしまい余計なメモリを消費してしまう」ため注意)

A.includes(:b).where(b: {id: nil})

参考

Ruby Tips - LEFT OUTER JOIN with ARel
MetaWhere Is About To Get Func-y - Ernie Miller

82
62
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
82
62