简体   繁体   中英

Mysql left join multiple columns from the same parent table

I'm having following problem with mysql query.

Given 2 tables


Person

Id | Name

1 | John Doe

2 | Jane Doe

3 | Pluto


Tickets

Id | Owner | Opener | AssignedTo

1 | 1 | 2 | 3

2 | 3 | 1 | 2

Owner, Opener, AssignedTo are Foreign keys linking to People Id


I need to make a query replacing Owner, Opener, AssignedTo columns with user names.

It's not a problem with just one column (it's enough to use left join), but I can't receive following output

select * from ....

1 | John Doe | Jane Doe | Pluto

2 | Pluto | John Doe | Jane Doe

Thanks in advance.

You could join Person multiple times.

SELECT t1.Id, t2.Name AS owner, t3.Name AS opener, t4.Name AS assignedTo
FROM Tickets t1
LEFT JOIN Person t2 ON t1.Owner = t2.Id
LEFT JOIN Person t3 ON t1.Opener = t3.Id
LEFT JOIN Person t4 ON t1.AssignedTo= t4.Id

SELECT Tickets. Id , POwner.Name AS Owner, POpener.Name AS Opener, PAssignedTo.Name AS AssignedTo FROM Tickets JOIN Person AS POwner ON Owner = POwner.Id JOIN Person AS POpener ON Opener = POpener.Id JOIN Person AS PAssignedTo ON AssignedTo = PAssignedTo.Id

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