2013-11-24 36 views
0

我有三個表:曖昧外連接時,左連接兩個表,但重複的記錄時,鏈接所有三個

Table1 - Customer profile 
customer id 
customer name 
customer country 
customer total sales 

Table2 - Contract list 
contract number 
customer id 
customer state 
contract sales 
business code 

Table3 - Business index 
business code 
business type 

每個customerxxx amount of contracts,每個'customer total sales'Table1等於求和'contract sales'Table2爲特定的客戶。

我想要列出的是所有客戶名稱,每個客戶的總銷售額,國家;還列出每個客戶的狀態和業務類型。

我的查詢試圖拉customer id, customer name, customer country, customer total sales from Table1customer state from Table2business type from Table3。但是,當我離開Join Table1.customer id - > Table2.customer id,並且左連接Table2.business代碼 - > Table3.business類型時,它會提取我想要的所有數據,但每個客戶都有xxx行重複記錄。

然後,我嘗試通過刪除一個連接並更改連接屬性來找出導致它的原因。

  1. 我刪除的任何一個聯接留下只有兩個人留下的鏈接表加盟;:它當'ambiguous outer join'彈出消息
  2. 我改變任何的一個連接要麼右連接或內部聯接
+1

你正在使用哪些DBMS?我不確定我完全理解你的問題,但聽起來你正在尋找一個「完全外連接」。你能添加一些示例數據和預期的輸出嗎? –

+0

你使用什麼查詢?你是否在使用group?還有@a_horse_with_no_name說,哪個DBMS? MySQL的行爲與MSSql或Oracle有所不同。你在查詢中使用group by? –

+1

@ user3027035 - 請包含您嘗試的查詢。另外,請用樣本起始數據更新您的問題,併爲該樣本檢索結果。順便說一句,除非你有性能問題,存儲在'客戶'的'總'行是乞求它不匹配'合同'的實際總數... ... –

回答

0

在T-SQL: 如表Customer_profileContract_list都有customer_idtable alias應該用來避免ambigous列名錯誤。也刪除重複的記錄Distinct關鍵詞應加。以下查詢應該工作:

select distinct cp.customer_id, 
     cp.customer_name, 
     cp.customer_country, 
     cp.customer_total_sales , 
     cl.customer_state, 
     bi.business_type 
from Customer_profile cp 
left join Contract_list cl on cp.customer_id = cl.customer_id 
left join Business_index bi on bi.business_code = cl.business_code ;