简体   繁体   English

SQL独特的两列组合

[英]SQL unique combination of two columns

Hi I'm stumped as to this problem as I need a unique combination of two instances of the same column. 嗨,我很难解决这个问题,因为我需要同一列的两个实例的独特组合。

Let's say I have a table Animal with a column Name. 假设我有一个表名为Animal的表。 I want all "unique" combinations of the animal name and not a repeat of it self or another already existing row. 我想要动物名称的所有“独特”组合,而不是重复它自己或另一个已经存在的行。

Sample data: 样本数据:

Name
-------
Mouse
Cat
Dog

The result I want is: 我想要的结果是:

Name1   Name2
-----   -----
Mouse   Cat
Mouse   Dog
Cat     Dog

I wrote the following query: 我写了以下查询:

SELECT DISTINCT A1.name AS Name1, A2.name as Name2
FROM Animal A1, Animal A2
WHERE A1.name <> A2.name;

Which netted me the following results instead: 这让我获得了以下结果:

Name1  Name2
-----  -----
Mouse  Cat
Mouse  Dog
Cat    Mouse
Cat    Dog
Dog    Mouse
Dog    Cat

I hope I'm making sense. 我希望我有意义。 I don't want a duplicate of both combination, whether it appears on the left or on the right. 我不想要两个组合的副本,无论它出现在左侧还是右侧。 As far as "Distinct" is concern the rows are distinct. 就“不同”而言,行是截然不同的。 So is there some way to eliminate the double up? 那么有什么方法可以消除双倍增长?

To find unique combinations, just change <> to < : 要查找唯一组合,只需将<>更改为<

WHERE A1.name < A2.name;
             ^^^

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

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