如何从SQL查询中删除反向重复项

如何从SQL查询中删除反向重复项,sql,postgresql,Sql,Postgresql,背景: 我有一个select查询,其中我有设备之间的链接。有些链接具有反向重复项,我希望在select查询中消除这些重复项 我已经搜索过类似的问题,尤其是这个问题: 但是这里的解决方案是有效的,因为它只有一个订单的副本,但它不适用于我的情况 下面是一组数据示例,以便于测试 在链路ip_src中插入ip_dst值“192.168.0.1”和“192.168.0.2”; 在链接ip_src中插入ip_dst值“192.168.0.1”和“192.168.0.3”; 在链路ip_src中插入ip_ds

背景: 我有一个select查询,其中我有设备之间的链接。有些链接具有反向重复项,我希望在select查询中消除这些重复项

我已经搜索过类似的问题,尤其是这个问题:

但是这里的解决方案是有效的,因为它只有一个订单的副本,但它不适用于我的情况

下面是一组数据示例,以便于测试

在链路ip_src中插入ip_dst值“192.168.0.1”和“192.168.0.2”; 在链接ip_src中插入ip_dst值“192.168.0.1”和“192.168.0.3”; 在链路ip_src中插入ip_dst值“192.168.0.5”和“192.168.0.4”; 在链接ip_src中插入ip_dst值“192.168.0.7”和“192.168.0.8”; 在链接ip_src中插入ip_dst值“192.168.0.8”和“192.168.0.7”; 预期结果:

'192.168.0.1', '192.168.0.2'  
'192.168.0.1', '192.168.0.3'  
'192.168.0.5', '192.168.0.4'  
'192.168.0.7', '192.168.0.8'  

如果您不关心最终结果集中的顺序,可以执行以下操作:

select distinct least(ip_src, ip_dst) as ip_src, greatest(ip_src, ip_dst) as ip_dst
from link ;
注意:这可能会导致原始表中没有成对的数据

如果您确实关心订购:

select ip_src, ip_dst
from link l
where ip_src <= ip_dst
union all
select ip_src, ip_dst
from link l
where ip_src > ip_dst and
      not exists (select 1 from link l2 where l2.ip_src = l.ip_dst and l2.ip_dst = l.ip_src);

注意:这将使用union all,因此不会删除重复项。您可以使用union删除重复项。

是要从表中删除它们,还是只在select查询的结果中抑制它们?@wildplasser我只想从结果中抑制它们。使用下面答案中最小和最大的函数对我来说很好。你还有其他选择吗?很有可能,最不重要的和最重要的都是不可取的。
SELECT *
FROM link l
WHERE NOT EXISTS (
        SELECT * from link nx 
                                -- The condition below is true for both the twins
        WHERE nx.ip_src = l.ip_dst AND nx.ip_dst = l.ip_src
                                -- this is true for only one of the twins
        AND nx.ip_src < nx.ip_dst
        );