SQL:自连接每行仅使用一次
可能的重复:
sql 中交叉联接的组合(不是排列)
I'当前有一个包含以下记录的表:
A1
A2
A3
B1
B2
C1
C2
其中相同的字母表示一些共同的标准(例如“字母”列的共同值)。我按照如下标准进行自连接:
SELECT mytable.*, self.* FROM mytable INNER JOIN mytable AS self
ON (mytable.letter = self.letter and mytable.number != self.number);
此连接给出类似以下内容:
A1 A2
A2 A1
A1 A3
A3 A1
A2 A3
A3 A2
B1 B2
B2 B1
C1 C2
C2 C1
但是,我只想将每对包含一次(组合而不是排列)。 我如何得到以下内容:
A1 A2
A1 A3
A2 A3
B1 B2
C1 C2
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
稍微更改 JOIN 条件将实现您想要的效果。
而不是:
use
这将仅包括
self.number
大于mytable.number
的组合,这实际上限制了结果为每个组合的一个有效排序...Changing the JOIN condition slightly will achieve what you want..
Instead of:
use
This will only include combinations where
self.number
is greater thanmytable.number
which in effect restricts the results to one valid ordering of each combination...