简体   繁体   中英

how to join three tables without duplication in sql?

I have three tables...
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  

now i want to join tables on custName and itemName..
the result should be..

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  

i need to select ( custAddress and custGSTIN ) from t_custMaster And ( productHSN and productUnit ) from t_productMaster on the basis of custName and itemName respectively from t_quoteMaster and attach it to the end of t_quoteMaster..

I tried below query but if gives duplication of rows..

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'

Duplication when joining in a one to many basis is a common issue. You can use DISTINCT to remove duplicates.

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'

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