Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LEFT OUTER joins in Rails 3

I have the following code:

@posts = Post.joins(:user).joins(:blog).select 

which is meant to find all posts and return them and the associated users and blogs. However, users are optional which means that the INNER JOIN that :joins generates is not returning lots of records.

How do I use this to generate a LEFT OUTER JOIN instead?

like image 621
Neil Middleton Avatar asked Jul 14 '10 10:07

Neil Middleton


People also ask

What is left outer join rails?

A left outer join (or just left join) is used to query a table based on matching and non-matching entries from a related table. Contrarily to an inner join, the left outer join will always return all the entries of the left table even if the join condition does not find any match on the right table.

How write query left outer join?

LEFT JOIN SyntaxON table1.column_name = table2.column_name; Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.

Is Outer join Left or right?

Left outer join includes the unmatched rows from the table which is on the left of the join clause whereas a Right outer join includes the unmatched rows from the table which is on the right of the join clause.

What is left join and inner join?

Different Types of SQL JOINs Here are the different types of the JOINs in SQL: (INNER) JOIN : Returns records that have matching values in both tables. LEFT (OUTER) JOIN : Returns all records from the left table, and the matched records from the right table.


1 Answers

@posts = Post.joins("LEFT OUTER JOIN users ON users.id = posts.user_id").               joins(:blog).select 
like image 81
Neil Middleton Avatar answered Oct 06 '22 08:10

Neil Middleton