Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining empty table to return all rows

I have a table (Table1) which has a composite primary key(Column1 + Column2). I am using it as a foreign key in another table (Table2).

Now I want to a SELECT statement to select all records from Table1 and Table2. But its returning me 0 rows, because table2 is Empty. I want all records from table1 and if it does not exist in table2, value of Columns in Table2 should be null.

I know, I only need to Join it. But I am not getting it right.

Thanks

like image 795
Scorpion Avatar asked Mar 21 '11 16:03

Scorpion


People also ask

What join returns all rows from both tables?

A CROSS JOIN , also known as a Cartesian JOIN, returns all rows from one table crossed with every row from the second table. In other words, the join table of a cross join contains every possible combination of rows from the tables that have been joined.

Which join Return all rows from left table?

The LEFT JOIN keyword returns all records from the left table (table1), and the matching records from the right table (table2).

Does LEFT join return all rows?

The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.

Does Inner join Return all rows?

An INNER JOIN is such type of join that returns all rows from both the participating tables where the key record of one table is equal to the key records of another table. This type of join required a comparison operator to match rows from the participating tables based on a common field or column of both the tables.


1 Answers

SELECT * FROM Table1 T1
LEFT JOIN Table2 T2 ON T1.Id = T2.FK

FK is your foreign key on the second table. A Left Join will return all rows from table1 even if they don't exist in table2.

like image 197
Hallaghan Avatar answered Oct 11 '22 22:10

Hallaghan