开发者

SQL::Self join a table to satisfy a particular condition?

开发者 https://www.devze.com 2023-01-14 15:48 出处:网络
I have the following table: mysql> SELECT * FROM temp; +----+------+ id | a| +----+------+ |1 |1 | |2 |2 |

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 fo开发者_开发百科llowing 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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消