繁体   English   中英

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

[英]Remove reverse duplicates from an SQL query

假设查询结果应该返回字符串对(x,y)的列表。 我试图消除反向重复。 我的意思是,如果(x,y)是结果之一,(y,x)不应该在以后出现。

例:

column 1 (foreign key)    column 2 (int)     column 3 (string)
4                         50                 Bob
2                         70                 Steve 
3                         50                 Joe

此表中显示的人可以多次出现,具有不同的第2列值。

我的查询需要打印具有相同列2值的每对名称:

select e.column3, f.column3 from example as e, example as f where e.column2 = f.column2 

(Bob, Bob)
(Bob, Joe)
(Joe, Bob)
(Joe, Joe)

我升级了查询,以便删除双打:

select e.column3, f.column3 from example as e, example as f where e.column2 = f.column2
       and e.column3 <> f.column3

(Bob, Joe)
(Joe, Bob)

现在我希望它只返回:

(Bob, Joe). 

(乔,鲍勃)是一个反向复制,所以我不希望它在结果中。 无论如何在一个查询中处理它?

首先,欢迎来到2012年。我们已经使用逗号从相关表中迁移出来。 它在ANSI 89中被引入,但严重缺乏。 现在,正确的方法是使用ANSI 92/99/2003 JOIN语法编写查询。

解决问题的方法是将双向不等式<>转换为单向不等式 ,或者<>无论您喜欢哪种方式。

select e.column3, f.column3
from example as e
join example as f on e.column2 = f.column2 and e.column3 < f.column3
select e.column3, f.column3 from example as e, example as f where e.column2 = f.column2
       and e.column3 <> f.column3 where e.id < f.id

添加一个简单的where子句应该这样做。

暂无
暂无

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

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