将单个列连接到两个单独的列中

时间:2018-12-10 07:11:52

标签: sql oracle oracle-apex

我有一个person表,该表存储人物姓名:

personid    firstname   lastname
526         Joe         Burnaby
527         Andy        Brandt
528         Ben         Oxfold

这些人存储在customeremployee表中

customerid  personid
745         526
746         527

employeeid  personid
628         528

然后有一个training表,它按原样存储每一列

trainingid  trainerid   customerid  rating
900         628         745         4
901         628         751         2

如何编写同时显示两个名称的Select? 预期输出应为

Trainer     Customer    Rating
Ben Oxfold  Joe Burnaby 4
Ben Oxfold  Andy Brandt 2

我不确定如何为此编写一个Select,因为我碰到了我选择的列中的墙:

SELECT 
person.firstname||person.lastname AS "Trainer",
person.firstname||person.lastname AS "Customer",
rating
FROM training
JOIN employee ON training.trainerid=employee.employeeid
JOIN customer ON training.customerid=customer.customerid
JOIN person ON employee.personid=person.personid
JOIN person ON customer.personid=person.personid;

我尝试过此操作,但是很明显,它只会在两行中仅显示您首先加入的人。

1 个答案:

答案 0 :(得分:1)

对于正确的join子句,应使用别名两次将人员表联接

SELECT   p1.firstname||' '||p1.lastname AS Trainer
       , p2.firstname||' '||p2.lastname AS Customer
       , t.rating
FROM training t 
INNER JOIN  employee e ON e.employeeid = t.trainerid 
INNER JOIN customer c ON c.customerid = t.customerid 
INNER JOIN person p1 ON p1.personid = e.personid 
INNER JOIN person p2 ON p2.personid = c.personid