SQL连接3个表来输出名称

时间:2017-06-21 11:40:50

标签: mysql sql

有3个表

客户

(CustID,FirstName,LastName)

艺术家

(ArtistID,FirstName,LastName)

Customer_Artist_Interest

(CustID,ArtistID)

我必须按照客户姓氏中艺术家姓氏的字母顺序链接3个表格,其中包括所有客户的姓名和每个客户感兴趣的艺术家的姓名。输出应如下所示:

A.LastName    A.FirstName     C.LastName    C.FirstName    

2 个答案:

答案 0 :(得分:0)

一些联接应该可以解决问题:

SELECT   a.LastName, a.FirstName, c.LastName, c.FirstName
FROM     Customer c
JOIN     Customer_Artist_Interest cai ON c.CustId = cai.CustId 
JOIN     Artist a ON cai.ArtistId = a.ArtistId
ORDER BY a.LastName, a.FirstName, c.LastName, c.FirstName

答案 1 :(得分:0)

select c.LastName,
       c.FirstName,
       a.LastName,
       a.FirstName,
  from Customer c,
       Artist a,
       Customer_Artist_Interest i
 where c.CustID = i.CustID
   and a.ArtistID = i.ArtistID
 order by c.LastName, c.FirstName, a.LastName, a.FirstName;