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

How to get value from the second table if it's null in the first one

I have a little issue with a SQL query. So. I have three tables: Artists, Albums and Songs. Songs belong to some Album OR some Artist (only one from these two). Albums belong to only Artists. And I want to receive all recordings of songs that are in albums and that are without them with the name of the artist in each. How to do that?

Code that doesn’t work:

select song_name, genre, lyrics, 
concat(first_name, ' ', last_name) as full_name, album_name
from songs 
left join artists on songs.artist_id = songs.artist_id
left join albums on artists.artist_id = albums.artist_id

Result of this code

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

Instead of this, I want to see the name of each artist whether he has an album or not.

>Solution :

SELECT
    song_name,
    genre,
    lyrics, 
    CONCAT(first_name, ' ', last_name) as full_name,
    album_name
FROM songs
LEFT JOIN albums
       ON songs.album_id = album.id
LEFT JOIN artists
       ON songs.artist_id = artists.id OR albums.artist_id = artist.id

I’m pretty sure this’ll do it!

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