0

I've got a relation/table and I am trying to put together (select) each ID with each others without taking any result where the ID is twice in the pair nor the pairs that are already present in reverse order (i.e pair [1,2] and pair [2,1] are the same) I only manage to remove the pairs where the ID is repeated twice (i.e [1,1], [2,2], [3,3] and so on) by doing so:

SELECT a.id first, b.id second
FROM myrelation a, myrelation b
WHERE a.id != b.id;

I went from this:

    |ID|attr1|attr2|...
    |1 |value|value|...
    |2 |value|value|...
    |3 |value|value|...

to this:

    |first|second|
    |  1  |   2  |
    |  1  |   3  |
    |  2  |   1  |
    |  2  |   3  |
    |  3  |   1  |
    |  3  |   2  |

when I actually want this:

    |first|second|
    |  1  |   2  |
    |  1  |   3  |
    |  2  |   3  |

can anyone please help!!? Thank you

4

1 回答 1

1

很简单,取组合表的对角线(就像@RamblinMan 说的):

SELECT a.id first, b.id second
FROM myrelation a, myrelation b
WHERE a.id < b.id;
于 2013-10-01T07:05:13.537 回答