将表两次联接在一起,每个表具有相同字段的两个不同值

时间:2018-11-07 23:43:35

标签: sql oracle

我有一条记录,其中包含两个与之相关的人的记录。人员记录是卖方(人员代码= 20)和客户(人员代码= 1)。我想要买卖双方的城市。我以为这很简单,但似乎无法使其正常工作-我没有任何结果。 Folderpeople表只是将我的文件夹与我的人相关联。

select f.folderid, f.foldername, fp.peoplecode, 
p.addrcity as clientcity, p2.addrcity as sellercity 
from folder  f
join folderpeople fp on fp.folderid = f.folderid 
join people p on fp.peopleid = p.peopleid and fp.peoplecode = 1 
join people p2 on fp.peopleid = p2.peopleid and fp.peoplecode = 20 ; 

4 个答案:

答案 0 :(得分:1)

问题是您只加入一次folderpeople表,因此您永远无法获得任何行。试试这个:

select f.folderid, f.foldername, fp.peoplecode, 
p.addrcity as clientcity, p2.addrcity as sellercity 
from folder  f 
join folderpeople fp1 on fp1.folderid = f.folderid 
join people p on fp1.peopleid = p.peopleid and fp1.peoplecode = 1 
join folderpeople fp2 on fp2.folderid = f.folderid 
join people p2 on fp2.peopleid = p2.peopleid and fp2.peoplecode = 20

此外,如果您没有每个文件夹都同时拥有卖方和客户,我将使用外部联接。

答案 1 :(得分:0)

尝试这个让我知道它是否有效。

with sellers as
  (select peopleid, addrcity from people where peoplecode = 20),
clients as 
  (select peopleid, addrcity from people where peoplecode = 1)
select f.folderid, f.foldername, fp.peoplecode, 
       c.addrcity as clientcity, s.addrcity as sellercity 
 from folder  f
 join folderpeople fp on fp.folderid = f.folderid 
 join sellers s on fp.peopleid = s.peopleid 
 join clients c on fp.peopleid = c.peopleid; 

答案 2 :(得分:0)

我怀疑您只需要left join s

select f.folderid, f.foldername, fp.peoplecode, 
       p.addrcity as clientcity, p2.addrcity as sellercity 
from folder f join
     folderpeople fp 
     on fp.folderid = f.folderid left join
     people p
     on fp.peopleid = p.peopleid and
        fp.peoplecode = 1 left join
     people p2
     on fp.peopleid = p2.peopleid and fp.peoplecode = 20 ; 

您没有行,因为fp.peoplecode在同一行中不能同时是“ 1”和“ 20”。

这应该解决您没有行的问题。它可能仍然不是您想要的结果集的结构。如果不是这种情况,请问另一个问题,并提供适当的样本数据和所需结果。

答案 3 :(得分:0)

我开了枪-兰迪的回答给出了结果-但给了我两行给大家。但这为我指明了正确的方向。当我将Randy的解决方案与mdem7的解决方案结合使用时,我发现了一个可行的解决方案。

with sellers as (select fp.folderid, p.peopleid, fp.peoplecode, p.addrcity, 
     p.addrpostal from folderpeople fp , people p where fp.peopleid = p.peopleid and 
     fp.peoplecode = 20), 
clients as 
     (select fp2.folderid, p2.peopleid, fp2.peoplecode, p2.addrcity, p2.addrprovince, 
     p2.addrpostal, p2.namelast, p2.namefirst from folderpeople fp2, people p2  where 
     fp2.peopleid = p2.peopleid and fp2.peoplecode = 1)
select c.namelast as ClientLast, c.namefirst as ClientFirst, f.issuedate, 
     c.addrcity as "Client City", s.addrcity as "Seller City"
     from folder  f
        left join sellers s on f.folderid = s.folderid  
        left join clients c on f.folderid = c.folderid;