SQL :: Self连接表以满足特定条件?

时间:2010-09-04 01:58:35

标签: sql mysql

我有下表:

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

我想获得以下输出:

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

但我遇到了一个小问题。我写了以下查询:

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

但我的输出如下:

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

有人能告诉我如何将其转换为所需的输出吗?我试图获得一个只生成连续值的表单。我的意思是,如果2大于1而3大于2,我不希望3大于1。

1 个答案:

答案 0 :(得分:3)

选项1:“三角连接” - 二次复杂度

 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;`

选项2:“Pseudo Row_Number()” - 线性复杂度

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