Join 3 tables in SQLite database

前端 未结 3 1140
陌清茗
陌清茗 2021-01-31 09:34

I have 3 tables in SQLite database:

Songs:

_id | name | length | artist_id (foreign key) | album_id (foreign key)

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-31 09:59

    Try this select, may by the Artists is more important than others, so the Songs come trough Artists and Albums from Songs.

    SELECT
      Songs._id AS song_id,
      Songs.name AS song_name, 
      Songs.length, 
      Songs.artist_id AS artist_id, 
      Artists.name AS artist_name, 
      Songs.album_id AS album_id, 
      Albums.name AS album_name
    FROM 
     Artists
     LEFT JOIN Songs ON Songs.artist_id = Artists._id
     LEFT JOIN Albums ON Songs.album_id = Albums._id
    

    Also if there is no entry in Songs belonging to a particular artist or no entry in Albums belonging to a particular song, you will still get the artist entry thanks to the LEFT JOIN. If you would like to return only artists with songs and albums, use JOIN instead.

提交回复
热议问题