mysql cross join, but without duplicated pair?

自古美人都是妖i 提交于 2019-12-06 01:12:31

问题


Let's say I have the following row in my table

table rows

id
63
64
65
66
67
68

if I run the following query, I get 30 rows.

SELECT r1.id, r2,id 
  FROM rows AS r1 
    CROSS JOIN rows AS r2 
  WHERE r1.id!=r2.id

result:

63  64
65  64
66  64
67  64
68  64
64  63
65  63
66  63
67  63
68  63
63  65
64  65
66  65
67  65
68  65
63  66
64  66
65  66
67  66
68  66
63  67
64  67
65  67
66  67
68  67
63  68
64  68
65  68
66  68
67  68

how would I get the following result instead of the above?

63,64  
63,65   
63,66
63,67
63,68

64,65
64,66
64,67
64,68

65,66
65,67
65,68

66,67
66,68

67,68

as you see, I don't want to get both 63,64 and 64,63, for example.


回答1:


Simple, only join with values higher than the current one.

select r1.id, r2,id 
from rows r1 
cross join rows r2 
where r1.id < r2.id



回答2:


Just add one condition. Left side to be always smaller then right. This will eliminate all the unwanted cases.

select r1.id, r2,id from rows as r1 cross join rows as r2 where r1.id!=r2.id and r1.id <r2.id


来源:https://stackoverflow.com/questions/5381757/mysql-cross-join-but-without-duplicated-pair

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!