combinations (not permutations) from cross join in sql

我与影子孤独终老i 提交于 2019-11-26 14:24:07

问题


If I have a table that I'd like to cross join to itself, how can I remove the duplicate rows? Or to put it another way, how can I do a "order doesn't matter" cross join?

So for example, if I have a table T:

field |
-------
   A  |
   B  |
   C  |

and I cross join to itself so that i don't get the A | A rows

T as t1
cross join
T as t2
  on t1.field != t2.field

I would get the following:

field | field
------+-------
  A   |   B
  A   |   C
  B   |   A
  B   |   C
  C   |   A
  C   |   B

However, to me A, B is the same as B, A.

Is there a good way to remove these duplicates? In other words, I want the combinations not the permutations.


回答1:


T as t1
inner join
T as t2
  on t1.field < t2.field

FWIW, you can just use INNER JOIN for this, it's not strictly a CROSS JOIN. MySQL (and perhaps some other RDBMS) treats these two types of join as identical, but in ANSI SQL, a cross join has no join condition -- it's a deliberate Cartesian product.



来源:https://stackoverflow.com/questions/7112513/combinations-not-permutations-from-cross-join-in-sql

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