SQL: self join using each rows only once [duplicate]

ぐ巨炮叔叔 提交于 2019-12-04 18:55:04

问题


Possible Duplicate:
combinations (not permutations) from cross join in sql

I've currently got a table with the following records:

A1
A2
A3
B1
B2
C1
C2

Where the same letter denotes some criteria in common (e.g. a common value for the column 'letter'). I do a self join on the criteria as follows:

SELECT mytable.*, self.* FROM mytable INNER JOIN mytable AS self 
   ON (mytable.letter = self.letter and mytable.number != self.number);

This join gives something like the following:

A1 A2
A2 A1
A1 A3
A3 A1
A2 A3
A3 A2
B1 B2
B2 B1
C1 C2
C2 C1

However, I only want to include each pair once (a combination instead of a permutation). How would I get the following:

A1 A2
A1 A3
A2 A3
B1 B2
C1 C2

回答1:


Changing the JOIN condition slightly will achieve what you want..

Instead of:

ON (mytable.letter = self.letter and mytable.number != self.number)

use

ON (mytable.letter = self.letter and mytable.number > self.number)

This will only include combinations where self.number is greater than mytable.number which in effect restricts the results to one valid ordering of each combination...



来源:https://stackoverflow.com/questions/7452981/sql-self-join-using-each-rows-only-once

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!