简体   繁体   中英

SQL left JOIN with 4 columns

i have two tables

IDartist     name
----------- -----------
1           akon
2           50 cent

IDsong    name   IDartist   IDauthor   IDcomposer   IDmusicProducer
------    ----   --------   --------   ---------    ---------------
1         lonley    1         2           1              2

how i out the name of whice IDartist,IDauthor,IDcomposer,IDmusicProducer ?

i tried to do this and its not working:

SELECT
songs.`IDsong`,
songs.`IDartist`,
songs.`name`,
songs.`IDgenre`,
songs.`IDauthor`,
songs.`IDcomposer`,
songs.`IDmusicProducer`,
artists.`name` As artists_name,
songs_genres.`name` As genres_name
FROM `songs`
LEFT OUTER JOIN `artists` ON (songs.`IDartist` = artists.`IDartist` OR songs.`IDauthor` = artists.`IDartist` OR songs.`IDcomposer` = artists.`IDartist` OR songs.`IDmusicProducer` = artists.`IDartist`)
LEFT OUTER JOIN `songs_genres` ON (songs.`IDgenre` = songs_genres.`IDgenre`)
WHERE songs.`IDsong`=XXX

In order to get the names of the artist, author, composer, and producer, you will have to join the artists table to the songs table for separate times. The query should look something like the following:

SELECT
s.IDsong, s.name,
a1.name AS artists_name,
a2.name AS author_name,
a3.name AS composer_name,
a4.name AS producer_name,
sg.name AS genres_name
FROM songs AS s
  JOIN artists AS a1 ON s.IDartist = a1.IDartist
  JOIN artists AS a2 ON s.IDauthor = a2.IDartist
  JOIN artists AS a3 ON s.IDcomposer = a3.IDartist
  JOIN artists AS a4 ON s.IDmusicProducer = a4.IDartist
  JOIN songs_genres AS sg ON s.IDgenre = sg.IDgenre

If there may not be an artist, author, composer, and producer for a record then you will have to use LEFT JOIN on the tables instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM