如何从 INNER JOIN 中删除重复/倒排的行

Ant*_*ony 1 mysql sql inner-join

我使用 SQL 从表中提取数据,还使用 ​​INNER JOIN 选择具有链接值/列的行,并将它们附加到一大行中。

下表:

   | name    |   value    |   num |
   | James   |   HEX124   |   1   |
   | James   |   JEU836   |   4   |
Run Code Online (Sandbox Code Playgroud)

我现在使用以下 SQL 将这两行连接成一行:

SELECT  a.name, a.value, a.num, b.name, b.value, b.num
FROM MY_TABLE a
INNER JOIN MY_TABLE b ON a.name = b.name //Inner joining where the name is the same
WHERE a.value <> b.value // where the values are NO the same
Run Code Online (Sandbox Code Playgroud)

结果:

   | a.name  |   a.value  | a.num | b.name  |   b.value  | b.num |
   | James   |   HEX124   |   1   |  James  |   JEU836   |   4   |
   | James   |   JEU836   |   4   |  James  |   HEX124   |   1   |
Run Code Online (Sandbox Code Playgroud)

正如您在结果中看到的,这是有效的,但它返回了所有可能的结果,我只想返回其中一行,因为它几乎重复/反转了它们。

也许只返回第一行,其中 a.name 是重复的?

期望的结果:

   | a.name  |   a.value  | a.num | b.name  |   b.value  | b.num |
   | James   |   HEX124   |   1   |  James  |   JEU836   |   4   |
Run Code Online (Sandbox Code Playgroud)

谢谢

Gor*_*off 5

只需更改:

a.value <> b.value
Run Code Online (Sandbox Code Playgroud)

到:

a.value < b.value
Run Code Online (Sandbox Code Playgroud)

我会将条件放在ON子句中,如下所示:

SELECT a.name, a.value, a.num, b.name, b.value, b.num
FROM MY_TABLE a INNER JOIN
     MY_TABLE b
     ON a.name = b.name AND a.value < b.value;
Run Code Online (Sandbox Code Playgroud)