从表连接中选择不同的有序对

时间:2016-08-26 03:25:44

标签: mysql select

请考虑两个带名字的表格。它们由表A id连接,因此两个名称相关联 是否有MySQL查询返回不同顺序的不同名称对?

第一张表:

table_a
+-----------+--------------+
|    id     |     name     |
+-----------+--------------+
|     1     |     John     |
+-----------+--------------+
|     2     |     Jane     |
+-----------+--------------+ 
|     3     |     Jane     |
+-----------+--------------+
|     4     |     Sammy    |
+-----------+--------------+    

第二张表:

table_b
+-----------+-------------------+-------------+
|    id     |     id_table_a    |    name     |
+-----------+-------------------+-------------+
|    1      |          1        |    Jane     |
+-----------+-------------------+-------------+
|    2      |          2        |    John     |
+-----------+-------------------+-------------+
|    3      |          3        |    Sammy    |
+-----------+-------------------+-------------+
|    4      |          4        |    Tara     |
+-----------+-------------------+-------------+

期望的结果

(John, Jane)
(Jane, Sammy)  
(Sammy, Tara)

提前致谢!

1 个答案:

答案 0 :(得分:2)

以下是使用leastgreatest的一个选项:

select distinct least(a.name, b.name), greatest(a.name, b.name)
from table_a a 
  join table_b b on a.id = b.id_table_a