MySQL,从一个表中加入两行并忽略双重

时间:2014-06-07 12:29:37

标签: mysql sql join

我有一张桌子"用户"像这样:

| uid | username |
|  1  | Jack     |
|  2  | John     |
|  3  | Robert   |

使用我的请求:

SELECT u1.username, u2.username FROM user u1 JOIN user u2

使用此请求,我得到一个这样的表:

| uid | username | uid | username |
|  1  | Jack     |  1  | Jack     |
|  1  | Jack     |  2  | John     |
|  1  | Jack     |  3  | Robert   |
|  2  | John     |  1  | Jack     |
|  2  | John     |  2  | John     |
|  2  | John     |  3  | Robert   |
|  3  | Robert   |  1  | Jack     |
|  3  | Robert   |  2  | John     |
|  3  | Robert   |  3  | Robert   |

如何删除其中一个二重奏?

|  1  | Jack     |  2  | John     |
|  2  | John     |  1  | Jack     |

1 个答案:

答案 0 :(得分:3)

您希望用户表1与用户表2的所有组合。我相信这将实现此目的:

SELECT u1.id, u1.name, u2.id u2.name
FROM User u1
INNER JOIN User u2
WHERE u1.id >= u2.id

这会得到以下结果:

| uid | username | uid | username |
|  1  | Jack     |  1  | Jack     |
|  2  | John     |  1  | Jack     |
|  2  | John     |  2  | John     |
|  3  | Robert   |  1  | Jack     |
|  3  | Robert   |  2  | John     |
|  3  | Robert   |  3  | Robert   |