2009-10-03 73 views
1

此表:鮮明的多列

mysql> select * from work; 
+------+---------+-------+ 
| code | surname | name | 
+------+---------+-------+ 
| 1 | John | Smith | 
| 2 | John | Smith | 
+------+---------+-------+ 

我想獲得對代碼其中姓名是平等的,所以我這樣做:

select distinct A.code, B.code from work A, work B where A.name = B.name group by A.code, B.code; 

不過,我得到以下結果返回:

+------+------+                       
| code | code |                       
+------+------+                       
| 1 | 1 | 
| 1 | 2 | 
| 2 | 1 | 
| 2 | 2 | 
+------+------+ 

正如您所看到的,該結果有2個重複項,顯然來自笛卡爾積。我想知道如何才能做到這一點,使它只輸出:

+------+------+                       
| code | code |                       
+------+------+                       
| 1 | 2 | 
+------+------+ 

任何線索?謝謝!

回答

2

這應該工作(假定code是主鍵):

SELECT A.code, B.code 
FROM work A, work B 
WHERE A.name = B.name AND A.code < B.code 
2

試試這個

Select A.Code, B.Code 
    From work a 
    Join work b 
     On A.surname = b.surname 
      And A.Name = B.Name 
      And A.Code > B.Code 

您需要使用A.Code> B.Code而不是!=消除類型的受騙者

{1,2}和{2,1}

(如果你只在乎當名稱是一樣的,而不是姓,消除一個連接條件,謂詞)