简体   繁体   English

SQL左联接有4列

[英]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 ? 我如何确定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. 为了获得艺术家,作家,作曲家,和制片人的名字,你将不得不加入artists表的songs表单独倍。 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. 如果可能没有艺术家,作家,作曲家和制作人来做唱片,那么您将不得不在表上使用LEFT JOIN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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