Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MySQL – Select from 2 tables even the other table is empty

I have 2 tables consisting of artists and tracks.

Artist
| id       | name           |
| -------- | -------------- |
| 1        | John Doe       |
| 2        | Dave Wang      | 

Tracks
| id       | artist_id      | title          |
| -------- | -------------- | -------------- |
| 1        | 1              | Song 1         |
| 2        | 1              | Song 2         |

I tried

SELECT a.name, b.title FROM Artist a, Tracks b WHERE a.id = b.artist_id

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It returns all the songs of John Doe.

Is there a way to add Dave Wang on the result even it’s just null on the title?

For example result

name title
John Doe Song 1
John Doe Song 2
Dave Wang null

>Solution :

Use an explicit left join:

SELECT a.name, b.title
FROM Artist a
LEFT JOIN Tracks b
    ON a.id = b.artist_id;

As a side note, your current query is using the old school implicit join syntax. The version I gave above is the correct way of writing the join.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading