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
).
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 .
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.
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.
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')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With