MySQL,有没有办法使用多个别名?

时间:2012-11-24 00:21:32

标签: mysql

鉴于我们有一个包含表格的数据库:
“artist”(列:name,id)和
“song”(title,composers_id,songwriters_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,但我不确定如何...

3 个答案:

答案 0 :(得分:4)

您必须从表艺术家中选择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;

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

答案 1 :(得分: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

答案 2 :(得分:0)

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

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

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