Home > Software design >  MySQL - Select from 2 tables even the other table is empty
MySQL - Select from 2 tables even the other table is empty

Time:02-20

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

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

CodePudding user response:

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.

CodePudding user response:

Please try this query

SELECT a.id, a.name,b.title FROM artist as a LEFT JOIN tracks as b on a.id = b.artist_id;

  • Related