4

假设我们有一个包含以下表格的数据库:
“艺术家”(列:名称,id)和
“歌曲”(标题,作曲家_id,歌曲作者_id)。

我想用作曲家的名字和词曲作者的名字打印歌曲。我仅通过以下方式成功打印了作曲家的名字:

SELECT title, name AS Composers_Name 
  FROM artist, song 
    WHERE song.composers_id = artist.id;

我无法获取词曲作者的名字。
我尝试的是:

SELECT title, name AS Composers_Name, name AS Songwriters_name
  FROM artist, song 
    WHERE song.composers_id = artist.id AND song.songwriters_id = artist.id;

但这会返回作曲家和词曲作者是同一个人的所有歌曲。我正在考虑使用 JOIN 但我不确定如何..

4

3 回答 3

6

您必须从表格艺术家中选择 2 次。

select s.title, a1.name AS Composer, a2.name as songwriter
from song s, artist a1, artist a2 
where s.composers_id = a1.id and s.songwriters_id = a2.id;

假设作曲家和作曲家都存储在艺术家表中。

于 2012-11-24T00:29:05.280 回答
2

使用左连接

SELECT s.title, c.name AS Composers_Name, a.name AS Songwriters_name
  FROM song s
  LEFT JOIN artist a ON s.songwriters_id = a.artistID
  LEFT JOIN artist c ON s.composers_id = c.artistID
于 2012-11-24T00:26:43.750 回答
0

我建议使用 join OR 定义每个表别名来访问它们的字段。

SELECT a.title, a.name AS Composers_Name, s.name AS Songwriters_name
FROM artist a, song s 

但是在您的问题中,词曲作者姓名字段缺失。您可以按照这种方式访问​​它。

于 2012-11-24T00:35:33.370 回答