对于此表:
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 |
+------+------+
有任何线索吗?谢谢!
答案 0 :(得分: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}
(如果您只关心名称是否相同而不是姓氏,请从连接条件中删除该谓词)
答案 1 :(得分:2)
这应该有效(假设code
是主键):
SELECT A.code, B.code
FROM work A, work B
WHERE A.name = B.name AND A.code < B.code