繁体   English   中英

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

[英]How to remove reverse duplicates from a SQL query

上下文:我有一个选择查询,我在设备之间有链接。 有些链接有“反向重复”,我想在select查询中删除它。

我已经搜索过类似的问题,尤其是这个问题: 从SQL查询中删除反向重复项

但这里的解决方案是有效的,因为它只与订单重复,但在我的情况下不适用。

这是查询的小提琴,数据示例更容易测试

http://sqlfiddle.com/#!17/214e6/7

insert into link (ip_src, ip_dst) values ('192.168.0.1','192.168.0.2');
insert into link (ip_src, ip_dst) values ('192.168.0.1','192.168.0.3');
insert into link (ip_src, ip_dst) values ('192.168.0.5','192.168.0.4');
insert into link (ip_src, ip_dst) values ('192.168.0.7','192.168.0.8');
insert into link (ip_src, ip_dst) values ('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 *
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
        );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM