如何在顶部重新排序具有特定值的 table

How to re-order a table with a certain value at the top

比如我有一个这样的table:

id
|02|
|01|
|03|
|05|
|04|

我需要将 table 更改为顶部的 05:

id
|05|
|01|
|02|
|03|
|04|

SELECT * FROM table1 ORDER BY id=05 desc,id 有效。但是我想改变 table.

ALTER TABLE table1 ORDER BY id 可以重新排序 table 数据。但是

ALTER TABLE table1 ORDER BY id=05 desc,id 无效。

我有一个旧版本没有订购 table 的应用程序,因此它在顶部显示“02”。我无法很快更新应用程序,所以我不得不重新订购 table。

ALTER table 不是用来操作数据的,它是用来修改 table 结构的。您最好的选择是 SELECT 进入临时 table、TRUNCATE,然后从临时 table.

重新插入

类似于:

SELECT *
INTO #temp
FROM table1
ORDER BY id=05 desc,id;

TRUNCATE table1;

INSERT INTO table1
SELECT * FROM #temp;

DROP #temp;

我无法在不更改 table 结构的情况下找到执行此操作的方法。 UPDATE 适用于这种排序,所以我必须插入一个新列,用一个变量更新它并改变它

ALTER TABLE table1 ADD COLUMN id2  INT NULL;
SET @i=1;
UPDATE table1 SET id2=(@i:=@i+1) ORDER BY id=05 desc,id
ALTER TABLE table1 ORDER BY id2;