SQL反转整列

时间:2015-10-04 18:28:32

标签: mysql sql reverse

有没有办法扭转整个列?

示例:

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

所以列ID应该颠倒,具有最后一个ID的记录应该是第一个,第二个是最后一个第一个和到目前为止。

最新的值有ID = 0和最旧的ID = n,这必须完全相反,否则我无法插入新记录。

3 个答案:

答案 0 :(得分:1)

您可以使用变量:

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列的值是什么,上述操作都会起作用。

答案 1 :(得分:0)

如果您的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),则需要采用不同的方法。

答案 2 :(得分:0)

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)