Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL JOIN rows if existing else fill with NULL

I have two tables of peoples names and properties. Some have no entries yet and I would like to create a full list of all people and their properties (if available) else have them listed with property "NULL". That's my simplicified example:

names

id     name
-------------
1      Jon
2      Peter
3      Sam
4      Bruce
...

properties

names_id    property
--------------------
1           foo
3           bar
...

desired result:

id     name     property
------------------------
1      Jon      foo
2      Peter    NULL
3      Sam      bar
4      Bruce    NULL
...

Thank you!

like image 725
Charma Avatar asked Dec 15 '22 07:12

Charma


2 Answers

Here, using join:

  select A.id, A.name, B.property
    from table1 A
    left outer join table2  B on A.id=B.names_id    
like image 64
jainvikram444 Avatar answered Dec 31 '22 14:12

jainvikram444


You can use left join in this case

select A.id,A.name,B.property
from names A
left join properties B
on A.id=B.names_id ;
like image 32
sam Avatar answered Dec 31 '22 13:12

sam