Join 3 tables in SQLite database

前端 未结 3 1135
陌清茗
陌清茗 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

    Using an explicit JOIN instead of an implicit one, the following should get what you want, although it is curious that your implicit join syntax did not return correct results in the first place. I have used a LEFT JOIN, to account for songs which do not have an associated artist or album, but that may not be necessary for your data set and an INNER JOIN could be used instead.

    I have also added column aliases to eliminate ambiguity when fetching rows, since you have similar column names in most of your tables (id, name).

    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 
     Songs 
     LEFT JOIN Artists ON Songs.artist_id = Artists._id
     LEFT JOIN Albums ON Songs.album_id = Albums._id
    

提交回复
热议问题