SQL:自连接每行仅使用一次

发布于 2024-12-05 05:14:24 字数 702 浏览 1 评论 0原文

可能的重复:
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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌面超妹 2024-12-12 05:14:24

稍微更改 JOIN 条件将实现您想要的效果。

而不是:

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

use

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

这将仅包括 self.number 大于 mytable.number 的组合,这实际上限制了结果为每个组合的一个有效排序...

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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文