加入3个表,以便对于其唯一记录,可以从第三个表中检索数据

问题描述 投票:0回答:1

我有3张桌子 - 表1(t1)具有accountnos表2(t2)的多个实例,其具有accountno的唯一实例及其customerno(t2具有与t1相比的附加帐户)表3(t3)具有customerno的详细信息

我想加入这三个表,这样对于来自t1的accountnos的唯一实例,我可以从t3中检索客户详细信息。如果客户详细信息在t3中不存在,我仍然希望来自t1的accountno。

例:

t1.accountno  
x  
x  
m  

t2.accountno t2.customerno  
x custid1  
y custid2  
z custid3  

t3.customerno t3.customername  
custid1 John  
custid2 Roy  

expected o/p  
t1.accountno t2.customerno t3.customername  
x custid1 John  
sql database
1个回答
1
投票

它是简单的内连接和分组,以避免重复的值

SELECT t1.accountno, t2.customerno, t3.customername FROM t1
    JOIN t2 cn ON t1.accountno = t2.accountno 
    JOIN t3 cn ON t2.customerno = t3.customerno 
Group By t1.accountno, t2.customerno, t3.customername
© www.soinside.com 2019 - 2024. All rights reserved.