简体   繁体   English

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

[英]Remove reverse duplicates from an SQL query

Let's say that a query result is supposed to return a list of string pairs (x, y). 假设查询结果应该返回字符串对(x,y)的列表。 I am trying to eliminate the reverse duplicates. 我试图消除反向重复。 What I mean is, if (x, y) was one of the results, (y, x) should not appear later. 我的意思是,如果(x,y)是结果之一,(y,x)不应该在以后出现。

example: 例:

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

The people represented in this table can appear multiple times with a different column 2 value. 此表中显示的人可以多次出现,具有不同的第2列值。

My query needs to print every pair of names that have the same column 2 value : 我的查询需要打印具有相同列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)

I upgraded the query so that it removes the doubles: 我升级了查询,以便删除双打:

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)

Now I want it to only return: 现在我希望它只返回:

(Bob, Joe). 

(Joe, Bob) is a reverse duplicate, so I don't want it in the result. (乔,鲍勃)是一个反向复制,所以我不希望它在结果中。 Is there anyway to handle that in one query? 无论如何在一个查询中处理它?

First of all, welcome to 2012. We have migrated away from relating tables using commas. 首先,欢迎来到2012年。我们已经使用逗号从相关表中迁移出来。 It was introdued in ANSI 89 but is severely lacking. 它在ANSI 89中被引入,但严重缺乏。 Nowaways, the correct way is to write queries using the ANSI 92/99/2003 JOIN syntax. 现在,正确的方法是使用ANSI 92/99/2003 JOIN语法编写查询。

The solution to your problem is to turn your bidirectional inequality <> into a unidirectional inequality , either < or > whichever you prefer. 解决问题的方法是将双向不等式<>转换为单向不等式 ,或者<>无论您喜欢哪种方式。

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

adding a simple where clause should do it. 添加一个简单的where子句应该这样做。

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

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