views:

40

answers:

1

I have the following table:

mysql> SELECT * FROM temp;
+----+------+
| id | a    |
+----+------+
|  1 |    1 | 
|  2 |    2 | 
|  3 |    3 | 
|  4 |    4 | 
+----+------+

I am trying to get the following output:

+----+------+------+
| id | a    | a    |
+----+------+------+
|  1 |    1 |    2 | 
|  2 |    2 |    3 | 
|  3 |    3 |    4 | 
+----+------+------+

but I am having a small problem. I wrote the following query:

mysql> SELECT A.id, A.a, B.a FROM temp A, temp B WHERE B.a>A.a;

but my output is the following:

+----+------+------+
| id | a    | a    |
+----+------+------+
|  1 |    1 |    2 | 
|  1 |    1 |    3 | 
|  2 |    2 |    3 | 
|  1 |    1 |    4 | 
|  2 |    2 |    4 | 
|  3 |    3 |    4 | 
+----+------+------+

Can someone tell me how to convert this into the desired output? I am trying to get a form where only the consecutive values are produced. I mean, if 2 is greater than 1 and 3 is greater than 2, I do not want 3 is greater than 1.

+3  A: 

Option 1: "Triangular Join" - Quadratic Complexity

 SELECT A.id, A.a, MIN(B.a) AS a 
 FROM temp A 
     JOIN temp B ON B.a>A.a 
 GROUP BY A.id, A.a;`

Option 2: "Pseudo Row_Number()" - Linear Complexity

select a_numbered.id, a_numbered.a, b_numbered.a
from 
(
select id,
       a,
       @rownum := @rownum + 1 as rn
  from temp
  join (select @rownum := 0) r
order by id

) a_numbered join (
select id,
       a,
       @rownum2 := @rownum2 + 1 as rn
  from temp
  join (select @rownum2 := 0) r
order by id

) b_numbered 
on b_numbered.rn = a_numbered.rn+1
Martin Smith
+1: Nicely done.
OMG Ponies
When I execute your query, I get just one row: 4, 4,1. Am I doing something wrong?
Legend
@legend - I needed to use a different variable name in the `option2`. I thought it would be reset but clearly not. Fixed now! You may well find that this second version performs better if you have a large table as the workload will grow linearly not quadratically as in option 1.
Martin Smith
@Martin: Thank you very much and +1 for the explanation too! :)
Legend