LEFT OUTER JOIN categorizations ON categorizations.author_id = authors.id INNER JOIN categories ON categories.id = categorizations.category_id AND categories.name = ? -- through 部分は dedup され、別名ごと増えない LEFT OUTER JOIN posts ON posts.id = categorizations.post_id rails/rails#40000
< ActiveRecord::Base enum label: [:default, :child] has_many :children, class_name: "Comment", foreign_key: :parent_id end Comment.includes(:children).where("children.label": "child") -- FROM comments LEFT OUTER JOIN comments children ON ... -- WHERE children.label = 1 WHERE を後から書き換えるのではなく、JOIN の alias を where に合わせる rails/rails#40106
JOIN comments ON comments.post_id = posts.id WHERE comments.id IS NULL SELECT * FROM posts WHERE NOT EXISTS ( SELECT 1 FROM comments WHERE comments.post_id = posts.id) SELECT * FROM posts WHERE id NOT IN ( SELECT post_id FROM comments)
( SELECT 1 FROM comments WHERE comments.post_id = posts.id) SELECT * FROM posts WHERE id IN ( SELECT post_id FROM comments) JOIN と違って、マッチの有無だけを見るので行が重複しない
1 FROM posts INNER JOIN comments ON comments.post_id = posts.id WHERE posts.author_id = authors.id) 相関 NOT EXISTS なら、経由テーブルが何段あってもレコード単位で問える rails/rails#58810