从此SQL连接中删除重复项

时间:2012-07-04 15:54:42

标签: postgresql join duplicates

我有下表

drop table names;
create table names(
    name    varchar(200),
    surname varchar(200),
    primary key(name, surname)
);

insert into names values ('john', 'doe');
insert into names values ('john', 'richards');

我想列出姓名相同的姓氏。 即我想要这个结果

----------+----------
 doe      | richards
 doe      | doe
 richards | richards

(这只是一个例子,真正的问题是完全不同的)

followig查询返回重复项

select n1.surname, n2.surname
from names n1 join names n2
on n1.name = n2.name;

 surname  | surname  
----------+----------
 doe      | richards
 doe      | doe
 richards | richards
 richards | doe

所以,我使用了leastgreatest postgresql函数,得到了我的结果。但是:leastgreatest不是标准SQL,我想知道是否存在更有效的解决方案,因为使用我现在无法想象的连接条件。

select distinct least(n1.surname, n2.surname), greatest(n1.surname,
n2.surname)
from names n1 join names n2
on n1.name = n2.name;

  least   | greatest 
----------+----------
 doe      | richards
 doe      | doe
 richards | richards

1 个答案:

答案 0 :(得分:2)

如果您只想要打破平局,请使用< >或> =或< =

SELECT n1.surname, n2.surname
FROM names n1 
JOIN names n2 ON n1.name = n2.name
WHERE n1.surname >= n2.surname
   ;