2017-09-17 135 views
1

當我在mssql上執行outer join時,我加入的列不會合並。外部連接返回多個連接列的副本

這裏是我的代碼:

select top 10 * from customer_behaviour_1P2014 full outer join 
customer_behaviour_2P2014 on customer_behaviour_1P2014.customer_identifier = customer_behaviour_2P2014.customer_identifier full outer join 
customer_behaviour_3P2014 on customer_behaviour_2P2014.customer_identifier = customer_behaviour_3P2014.customer_identifier 

這將返回3列標記customer_identifier,而不是1

我在做什麼錯?

如果它有什麼不同,我把客戶標識符作爲每個表中的索引。

回答

2

您正在選擇所有3個表中的所有列,並且每個表都有一個customer_identifier列(從ON條款推導)。

每個customer_identifier列的結果來自不同的表。匹配時值將相同,或者在沒有行匹配時爲NULL

指定明確的列列表而不是*以避免重複值。取而代之的是3個獨立customer_identifier列,用COALESCE函數返回的第一個非NULL值:

SELECT <other-columns>, 
COALESCE(customer_behaviour_1P2014.customer_identifier, customer_behaviour_2P2014.customer_identifier, customer_behaviour_3P2014.customer_identifier) AS customer_identifier 
FROM ... 
+0

有啥選擇所有列,並只選擇customer_identifier一次的方式嗎? – user1871528

+0

@ user1871528,我將其添加到我的答案中。 –