SQL 反转整列

SQL Reverse entire column

有没有办法反转整列?

示例:

ID    ColX    ColY    ColZ
0     001     010     100
1     002     020     200
2     003     030     300

应为:

ID    ColX    ColY    ColZ
0     003     030     300
1     002     020     200
2     001     010     100

所以Column ID应该倒过来,最后一个ID的记录应该是第一个,倒数第二个倒数第二个,直到现在。

最新的值ID = 0,最老的ID = n,这必须正好相反,否则我无法插入新记录。

您可以使用变量来完成:

SELECT t2.ID, ColX, ColY, ColZ
FROM (SELECT ID, ColX, ColY, ColZ,
             @row_number := @row_number + 1 AS rn
      FROM mytable
      CROSS JOIN (SELECT @row_number := 0) AS var
      ORDER BY ID) AS t1
INNER JOIN (  
      SELECT ID, @rn := @rn + 1 AS rn          
      FROM mytable
      CROSS JOIN (SELECT @rn := 0) AS var
      ORDER BY ID DESC) AS t2
ON t1.rn = t2.rn
ORDER BY t2.ID

Demo here

如果你想 UPDATE 那么你可以在 UPDATE 语句中使用上面的查询,如下所示:

UPDATE mytable AS t
INNER JOIN(
   SELECT ID, ColX, ColY, ColZ,
          @row_number := @row_number + 1 AS rn
   FROM mytable
   CROSS JOIN (SELECT @row_number := 0) AS var
   ORDER BY ID) AS t1 ON t.ID = t1.ID
INNER JOIN (  
      SELECT ID, @rn := @rn + 1 AS rn          
      FROM mytable
      CROSS JOIN (SELECT @rn := 0) AS var
      ORDER BY ID DESC) AS t2 ON t1.rn = t2.rn
SET t.ID = t2.ID

Demo here

无论 ID 列的值如何,以上都有效。

如果你的ID没有空格,那么你可以使用this select query:

SELECT
  max_id-ID AS ID,
  ColX,
  ColY,
  ColZ
FROM
  mytable CROSS JOIN (SELECT MAX(ID) AS max_id FROM mytable) m
ORDER BY
  ID

或这个 update query (但只有当 ID 不是主键时它才有效):

UPDATE
  mytable m1 CROSS JOIN (SELECT MAX(ID) as max_id FROM mytable) m
SET
  m1.ID = m.max_id - m1.ID

如果它是主键,你可以使用这个:

UPDATE
  mytable m1 CROSS JOIN (SELECT MAX(ID) as max_id FROM mytable) m
  INNER JOIN mytable m2 ON m1.ID = m.max_id - m2.ID
SET
  m1.ColX = m2.ColX,
  m1.ColY = m2.ColY,
  m1.ColZ = m2.ColZ

(请看here)

但如果您的 ID 列有间隙(例如 0、1、2、5、6),您需要采用不同的方法。

SELECT 
  @x - t.id AS new_id,
  t.* 
FROM tab t,
( SELECT @x:= max(id+1) FROM tab ) m;

MariaDB [tmp]> SELECT
    ->   @x - t.id AS new_id,
    ->   t.*
    -> FROM tab t,
    -> ( SELECT @x:= max(id+1) FROM tab ) m;
+--------+----+--------+---------------------+
| new_id | id | action | date                |
+--------+----+--------+---------------------+
|      7 |  1 |      2 | 2015-09-24 15:28:30 |
|      6 |  2 |      4 | 2015-09-24 15:29:26 |
|      5 |  3 |      2 | 2015-09-24 15:30:01 |
|      4 |  4 |      3 | 2015-09-24 15:30:55 |
|      3 |  5 |      1 | 2015-09-24 16:07:25 |
|      2 |  6 |      5 | 2015-09-24 16:10:25 |
|      1 |  7 |      4 | 2015-09-24 16:29:26 |
+--------+----+--------+---------------------+
7 rows in set (0.00 sec)