Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL issue: LEFT JOIN on empty table

Given a database with two tables X and Y, I have a query that should LEFT JOIN the two tables on attributes X.a1 and Y.b1. I used the following query:

SELECT X.a1, X.a2, Y.b1, Y.b2 FROM X LEFT JOIN Y ON (X.a1 = Y.b1)

I thought that would be good enough to work, even if Y is currently an empty table. However, the query breaks because table Y is empty, it seems. Is there any way to reformat this query so that even if Y is an empty table, the LEFT JOIN will not break? Or do I just need to always make sure that there is some data in table Y, even if it doesn't match anything in table X (hence the LEFT JOIN).

like image 399
ashays Avatar asked Mar 03 '10 17:03

ashays


People also ask

Can I use LEFT join without on?

In MySQL, it's possible to have a JOIN statement without ON as ON is an optional clause. You can just simplly JOIN two tables like this: SELECT * FROM table_a JOIN table_b; It will match each row from table_a to every row in table_b .

WHAT IF LEFT join is NULL?

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.

Why is a left join adding rows?

There are two line items for ID 1003 in the second table, so the result of the join will be 2 line items. So, if your secondary tables have more than one row for the key you're joining with, then the result of the join will be multiple rows, resulting in more rows than the left table.


2 Answers

Since you didn't post your actual SQL, i just make assumption here. My experience telling me that you might have a where clause that causes the SQL to return empty set.

SELECT X.a1, X.a2, Y.b1, Y.b2 FROM X LEFT JOIN Y ON (X.a1 = Y.b1)
WHERE Y.b3 = 'something'

The above SQL will return empty result set. You may need to modify your SQL into the following format, by bring up the problematic where clause to LEFT JOIN ON clause.

SELECT X.a1, X.a2, Y.b1, Y.b2 FROM X 
LEFT JOIN Y ON (X.a1 = Y.b1 and Y.b3 = 'something')
like image 186
poh Avatar answered Oct 05 '22 23:10

poh


Your table names are a little confusing. Is it X and Y, or X.a and Y.b?

If X and Y:

SELECT X.a1, X.a2, Y.a1, Y.b2 FROM X LEFT OUTER JOIN Y ON (X.a1 = Y.b1)

should bring back all X, with nulls for the Y.a1 and Y.b2 where there is no matching record.

like image 43
aw crud Avatar answered Oct 05 '22 22:10

aw crud