gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 11:49:23 24 4
gpt4 key购买 nike

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

我已经搜索过类似的问题,尤其是这个问题:Remove reverse duplicates from an SQL query

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

这里有一个带有数据示例的查询 fiddle ,以便于测试

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 删除重复项。

关于sql - 如何从 SQL 查询中删除反向重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46074621/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com