2017-08-06 81 views
1

我想要做的故事自聯接,使一對客戶,但我不希望同樣對出現兩次,我用這個代碼如何讓相同的字段在SQL自連接中不出現兩次?

SELECT DISTINCT A.customer_num AS ' num1' 
       , B.customer_num AS 'num2' 
       , A.customer_name AS 'name1' 
       , B.customer_name AS 'name2' 
       , A.city AS 'city' 
      FROM tbl_customer A 
       , tbl_customer B 
      WHERE A.customer_num <> B.customer_num 
       AND A.city = B.city ; 

它給我的記錄,但對得到重複,這就是我得到的結果My Result,如1和第6對是相同的,我得到了 ,我正在使用MySQL Workbench。

回答

2

由於您的自加入where條件是對稱(即A.customer_num <> B.customer_num),每對將在輸出中出現兩次。無論記錄是A還是B,因此將條件切換到不對稱將解決該問題。

當你在它時,切換到使用ANSI連接;您也不再需要DISTINCT

SELECT 
    A.customer_num AS 'num1' 
, B.customer_num AS 'num2' 
, A.customer_name AS 'name1' 
, B.customer_name AS 'name2' , 
A.city AS 'city' 
FROM tbl_customer A -- It does not matter if you use <or> below 
JOIN tbl_customer B ON A.customer_num > B.customer_num AND A.city = B.city 
+0

我還需要DISTINCT嗎?或不@dasblinkenlight –

+0

@HarryKashyap不,你應該可以刪除'DISTINCT'子句。 – dasblinkenlight

相關問題