我有下表
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
(这只是一个例子,真正的问题是完全不同的)
以下查询返回重复项
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
所以,我使用了least
和greatest
postgresql 函数,得到了我的结果。但是:least
并且greatest
不是标准 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