Sql 将表中的每一行与其他每一行进行一次和一次比较

Sql 将表中的每一行与其他每一行进行一次和一次比较,sql,postgresql,Sql,Postgresql,我有一个postgres表,里面有很多记录,我想和同一个表中的其他记录进行比较。考虑这个表。 create table temp (rec char(1)); 填充此数据: insert into temp (rec) values ('a'); insert into temp (rec) values ('b'); insert into temp (rec) values ('c'); insert into temp (rec) values ('d'); 并使用此SQL查询: se

我有一个postgres表,里面有很多记录,我想和同一个表中的其他记录进行比较。考虑这个表。

create table temp (rec char(1));
填充此数据:

insert into temp (rec) values ('a');
insert into temp (rec) values ('b');
insert into temp (rec) values ('c');
insert into temp (rec) values ('d');
并使用此SQL查询:

select a.rec, b.rec
from temp a, temp b 
这将返回16行(如预期的那样),但其中包括额外的行,其中“a”=“a”和“b”=“b”。要删除这些,我可以将查询更改为

select a.rec, b.rec
from temp a, temp b 
where a.rec <> b.rec
但是,它仍然会回拉一些重复项,它不仅会回拉一个'a'='b'的记录,而且还会回拉我不感兴趣的'b'='a'(我已经将记录'a'与记录'b'进行了比较,因此不想反过来做同样的比较)


那么,如何更改查询以将每一行与每一其他行进行一次比较,并且仅进行一次比较?

在上次查询中使用distinct:

select distinct least(a.rec, b.rec), greatest(a.rec, b.rec)
from temp a
  cross join temp b 
where a.rec <> b.rec;
选择不同的最小值(a.rec,b.rec),最大值(a.rec,b.rec)
来自临时工a
交叉连接温度b
其中a.rec b.rec;
表达式
least(a.rec,b.rec),magest(a.rec,b.rec)
b,a
转换为
a,b
,然后
distinct
删除重复项


在线示例:

只需将您的条件更改为
感谢没有名字的马-这对我非常有用。我的实时查询实际上包含10到数千行的数据,结果是100到数百万的结果。您的解决方案大大减少了这一点,并大大缩短了处理时间。
select distinct least(a.rec, b.rec), greatest(a.rec, b.rec)
from temp a
  cross join temp b 
where a.rec <> b.rec;
select a.rec, b.rec
from temp a join
     temp b 
     on a.rec < b.rec;