如何在sql中连接三个表而不重复?

时间:2017-10-18 03:13:34

标签: mysql sql sql-server join

我有三张桌子......
1)t_quoteMaster

quoteId  quoteNo  quoteDate  custName  itemName  itemQty  itemPrice  itemToal  
  10        2     17/10/17    cust1     item1       2        100       200   
  11        2     17/10/17    cust1     item2       5        20        100  

2)t_custMaster

custId  custName  custAddress  custGSTIN  custPhone
  10     cust1        US       123456789  123456789  
  11     cust2        UK       987654321  987654321

3)t_productMaster

productId  productName  productHSN  productUnit  productPrice
    15       item1      1111111111      kg           100  
    16       item2      2222222222     gram          20  
    17       item3      3333333333      kg           50  

现在我想在custName和itemName上连接表。
结果应该是......

quoteId  quoteNo  quoteDate  custName  itemName  itemQty  itemPrice  itemToal  productHSN  productUnit  custAddress  custGSTIN  
  10        2     17/10/17    cust1     item1       2        100       200     1111111111      kg           US       123456789
  11        2     17/10/17    cust1     item2       5        20        100     2222222222     gram          US       123456789  

我需要从 t_custMaster 和( productHSN productUnit)中选择( custAddress custGSTIN )来自 t_productMaster ,分别来自t_quoteMaster的 custName itemName ,并将其附加到t_quoteMaster的末尾。

我尝试了下面的查询,但是如果给出重复的行..

SELECT t_quoteMaster.*,
t_productMaster.productHSN,
t_productMaster.productUnit,
t_custMaster.custAddress,
t_custMaster.custGSTIN 
FROM t_quoteMaster
INNER JOIN t_productMaster
ON t_quoteMaster.itemName = t_productMaster.productName
INNER JOIN t_custMaster
ON t_quoteMaster.custName = t_custMaster.custName
where t_quoteMaster.quoteNo = '2'

1 个答案:

答案 0 :(得分:0)

以一对多方式加入时的复制是一个常见问题。您可以使用SELECT DISTINCT t_quoteMaster.*, t_productMaster.productHSN, t_productMaster.productUnit, t_custMaster.custAddress, t_custMaster.custGSTIN FROM t_quoteMaster INNER JOIN t_productMaster ON t_quoteMaster.itemName = t_productMaster.productName INNER JOIN t_custMaster ON t_quoteMaster.customerName = t_custMaster.custName where quoteNo = '2' 删除重复项。

NSOutlineView