2014-12-19 100 views
0

我遇到了問題INNER JOIN。有三個表格Customer,Regular a和Master。使用此查詢 ,我只得到記錄從customer多表內部加入SQL Server R2

查詢

Select 
    Customer.CustomerId, 
    Customer.RefId, 
    Regular.LicenseId, 
    Master.MasterId, 
    Master.FullName, 
    Master.Profile 
From 
    Customer 
Inner Join 
    Regular on Customer.RefId = Regular.Licenseid 
Inner join 
    master on regular.controlid = master.masterid Or customer.refid = master.masterid 

結果

enter image description here

從表CustomerRefId兼具記錄M000001和R000001。爲什麼結果只顯示REFID從R000001只有

數據源開始從客戶主是...

結果將包括客戶表中的所有行...

enter image description here

任何一個可以解決這個問題,並編輯我的查詢,以獲得從客戶表中的這兩種類型的記錄...

+0

能否請您加入到Regular.ControlID您原始查詢。您在比較中使用它,但在任何結果集中都沒有對它的引用。因此很難確定它正在發生什麼。 – KHeaney

+0

您的查詢是錯誤的,仔細查看您的客戶ID和結果集中的全名。他們不匹配。客戶04在客戶表中是南德,但Salunke在結果集中。我懷疑在主表加入OR是造成你的問題 – Sparky

+0

@ Sparky我認爲你還沒有理解查詢。 –

回答

1

從這個SO問題,似乎在您的連接中使用OR條件是一個壞主意:

https://stackoverflow.com/a/5901901/3915817

因此我只想切換查詢顧左右而言他。你可以做到這一點無論是使用外部聯接

Select Customer.CustomerId, 
     Customer.RefId, 
     Regular.LicenseId, 
     Coalesce(Mast1.MasterId, Mast2.MasterId) AS MasterId, 
     Coalesce(Mast1.FullName, Mast2.FullName) AS FullName, 
     Coalesce(Mast1.Profile, Mast2.Profile) AS Profile 
From Customer 
    Inner Join Regular on Customer.RefId = Regular.Licenseid 
    Left Outer Join master As Mast1 
     on regular.controlid = master.masterid 
    Left Outer Join master As Mast2 
     on customer.refid = master.masterid 
Where (Mast1.masterid Is Not Null 
    Or Mast2.MasterId Is Not Null) 

或者與聯盟條款

Select Customer.CustomerId, 
     Customer.RefId, 
     Regular.LicenseId, 
     Master.MasterId, 
     Master.FullName, 
     Master.Profile 
From Customer 
    Inner Join Regular on Customer.RefId = Regular.Licenseid 
    Inner Join master on regular.controlid = master.masterid 

Union 

Select Customer.CustomerId, 
     Customer.RefId, 
     Regular.LicenseId, 
     Master.MasterId, 
     Master.FullName, 
     Master.Profile 
From Customer 
    Inner Join Regular on Customer.RefId = Regular.Licenseid 
    Inner Join master on customer.refid = master.masterid