小编典典

无论列顺序如何,都显示不同的元组

sql

说我有以下结果

----------------------
|   col1  |   col2   |
----------------------
|    a    |    b     |
|    b    |    a     |
|    c    |    d     |
|    e    |    f     |
----------------------

无论列顺序如何,我都想获得不同的元组。换句话说,(a, b) 和 (b, a) 被认为是“相同的”,因为更改顺序会使一个与另一个相同 (a, b) == (a, b)。所以,执行查询后应该是:

----------------------
|   col1  |   col2   |
----------------------
|    a    |    b     | // or (b, a)
|    c    |    d     |
|    e    |    f     |
----------------------

任何查询专家都可以帮助我吗?我被困了几个小时,无法解决这个问题。

以下是我正在处理的详细场景。

我有以下关系:

Ships(name, country) // ("Lincoln", "USA") = "Ship Lincoln belongs to USA"
Battles(ship, battleName) // ("Lincoln", "WW2") = "Ship Lincoln fought in WW2"

我需要找到:列出所有在战斗中相互战斗的国家

通过执行以下查询,我能够找到所有对:

 SELECT DISTINCT c1, c2
 FROM
 (SELECT DISTINCT s1.country as c1, battleName as b1
  FROM Ships as s1, Battles
  WHERE s1.name = ship) as t1
 JOIN
 (SELECT DISTINCT s2.country as c2, battleName as b2
  FROM Ships as s2, Battles
  WHERE s2.name = ship) as t2
 ON (b1 = b2)
 WHERE c1 <> c2
 ```

执行上述查询的结果是:


| c1 | c2 |

| USA | Japan | // Row_1
| Japan | USA | // Row_2
| Germany | Great Britain | // Row_3
| Great Britain | Germany | // Row_4


```

但是 Row_1Row_2Row_3Row_4 相同。

我需要的是打印 Row_1Row_2 之一以及 Row_3Row_4

谢谢


阅读 201

收藏
2021-05-30

共1个答案

小编典典

Try it this way

SELECT DISTINCT
       LEAST(s1.country, s2.country) c1,
       GREATEST(s1.country, s2.country) c2
  FROM battles b1 JOIN battles b2
    ON b1.battlename = b2.battlename
   AND b1.ship <> b2.ship JOIN ships s1
    ON b1.ship = s1.name JOIN ships s2
    ON b2.ship = s2.name
HAVING c1 <> c2

Output:

|      C1 |            C2 |
|---------|---------------|
| Germany | Great Britain |
|   Japan |           USA |
2021-05-30