Mysql选择从表中移动一列

时间:2013-11-27 14:34:03

标签: mysql sql

我有一个MySQL表,如下所示:

-----
| 1 |
-----
| 3 |
-----
| 7 |
-----
| . |
-----
| . |
-----
| . |
-----
| n |
-----

是否可以从此表中选择具有以下内容的内容:

----------
| 1 || 3 |
----------
| 3 || 7 |
----------
| 7 || . |
----------
| . || . |
----------
| . || . |
----------
| n || n-1 |

3 个答案:

答案 0 :(得分:1)

我想,下面的查询最接近你想要的MySQL

mysql> select * from num;
+------+
| a    |
+------+
|    1 |
|    3 |
|    7 |
|   11 |
|   17 |
+------+

mysql> select @prev:=a FROM num ORDER BY a ASC LIMIT 1,1;
+----------+
| @prev:=a |
+----------+
|        3 |
+----------+
1 row in set (0.00 sec)

mysql> select @prev, t1.a, @prev:=t1.a from num t1;
+-------+------+-------------+
| @prev | a    | @prev:=t1.a |
+-------+------+-------------+
|     3 |    1 |           1 |  <= 1st row is dummy
|     1 |    3 |           3 |
|     3 |    7 |           7 |
|     7 |   11 |          11 |
|    11 |   17 |          17 |
+-------+------+-------------+
5 rows in set (0.00 sec)

mysql> select MAX(a), NULL FROM num;
+--------+------+
| MAX(a) | NULL |
+--------+------+
|     17 | NULL | <= last row founded here
+--------+------+
1 row in set (0.00 sec)

答案 1 :(得分:0)

关系数据没有行号或行排序的概念,因此使用(标准)SQL无法“移动1行”。如果您的表包含字段“rownumber”,则可以使用自联接:

SELECT t1.field, t2.field
  FROM mytable t1 join mytable t2 on(t1.rownumber = t2.rownumber+1)

但是正如BenM所说的那样:只是换一行并不太有意义,但如果你有其他任何加入标准,自联接是一个有用的工具。

答案 2 :(得分:0)

已经标记了答案。但是我这里是为其他用户发布的。

DECLARE @mytable table
(
    mycolumn varchar(10)
)

INSERT INTO @mytable 
SELECT '| 1 |' UNION ALL
-----
SELECT '| 3 |' UNION ALL
-----
SELECT '| 7 |' UNION ALL
----- 
SELECT '| . |' UNION ALL
-----
SELECT '| . |' UNION ALL
-----
SELECT '| . |' UNION ALL
-----
SELECT '| n |'

SELECT * FROM @mytable 

SELECT 
    t1.mycolumn, t2.mycolumn
FROM
(
    SELECT 
        ROW_NUMBER() OVER (ORDER BY mycolumn) as rownum, mycolumn
    from @mytable
) t1
INNER JOIN 
(
    SELECT 
        ROW_NUMBER() OVER (ORDER BY mycolumn)as rownum, mycolumn
    from @mytable
) t2 
on(t1.rownum = t2.rownum+1)
WHERE t2.rownum > 0

此查询适用于sql server。

请看以下基本上具有逻辑

的部分
SELECT 
    t1.mycolumn, t2.mycolumn
FROM
(
    SELECT 
        ROW_NUMBER() OVER (ORDER BY mycolumn) as rownum, mycolumn
    from @mytable
) t1
INNER JOIN 
(
    SELECT 
        ROW_NUMBER() OVER (ORDER BY mycolumn)as rownum, mycolumn
    from @mytable
) t2 
on(t1.rownum = t2.rownum+1)
WHERE t2.rownum > 0