日期:2014-05-16  浏览次数:20852 次

请问这样的问题的MySql查询语句怎么写?
现在有一个表,名字就叫作comment吧:
+------+
| id |
+------+
| 102 |
| 203 |
| 213 |
| 222 |
| 258 |
| 288 |
| 298 |
| 322 |
+------+

我想给他按照id顺序加上编号:

+---+-----+
| 编号 | id | 
+---+-----+
| 1 | 102 |
| 2 | 203 |
| 3 | 213 |
| 4 | 222 |
| 5 | 258 |
| 6 | 288 |
| 7 | 298 |
| 8 | 322 |
+----+----+
这个我能用以下语句实现:
SQL code
set @floor := 0; select @floor := @floor + 1 as '编号', comment.* from comment


然后我想得到编号4和其后面的2行,在这张表里就会得到如下结果:

+---+-----+
| 编号 | id | 
+---+-----+
| 4 | 222 |
| 5 | 258 |
| 6 | 288 |
+----+----+

按照这个实例的步骤,我想请问一般情况下的MySql语句怎么写。我才接触Sql,希望大家能帮助我。谢谢

------解决方案--------------------
SQL code
mysql> SELECT * FROM TA4;
+------+
| ID   |
+------+
|  102 |
|  203 |
|  213 |
|  222 |
|  258 |
|  288 |
|  298 |
|  322 |
+------+
8 rows in set (0.00 sec)

mysql> SET @NUM:= 0;
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT * FROM (
    -> SELECT *,@NUM:= @NUM + 1 AS '编号' FROM TA4) A ORDER BY 编号 LIMIT 3,3;
+------+------+
| ID   | 编号     |
+------+------+
|  222 |    4 |
|  258 |    5 |
|  288 |    6 |
+------+------+
3 rows in set (0.00 sec)

mysql>

------解决方案--------------------
set @floor := 0; select * from (select @floor := @floor + 1 as `编号`, comment.* from comment) t where `编号`>=4 limit 3;