Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select multiple tables when one table is empty in MySQL

Tags:

sql

mysql

I'm trying to do

SELECT * FROM a, b

However, it doesn't return anything if one of the tables is empty. How do I make it so it returns 'a' even if the other one is empty?

like image 436
Alex Avatar asked Jul 03 '10 11:07

Alex


3 Answers

Using two tables in the from clause is functionally equivalent to a cross join:

select  *
from    A
cross join
        B

This returns a row of A for every row in B. When B is empty, the result is empty too. You can fix that by using a left join. With a left join, you can return rows even if one of the tables is empty. For example:

select  * 
from    A
left join  
        B
on      1=1

As the condition 1=1 is always true, this is just like a cross join except it also works for empty tables.

like image 190
Andomar Avatar answered Oct 20 '22 05:10

Andomar


SELECT * FROM a LEFT JOIN b ON a.ID = b.ID

Will return everything from a even if b is empty.

like image 1
duraz0rz Avatar answered Oct 20 '22 06:10

duraz0rz


You should do a left join.

Like this

SELECT *
FROM A
 LEFT JOIN B ON A.ID = B.ID

Then you receive the rows in A and the respective row in B if exists.

like image 1
Bruno Costa Avatar answered Oct 20 '22 06:10

Bruno Costa