現有一張表: Greatersts

建表結構:
CREATE TABLE `Greatersts` (
`key` varchar(32) DEFAULT NULL,
`x` int(11) DEFAULT NULL,
`y` int(11) DEFAULT NULL,
`z` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
插入數據:
INSERT INTO `Greatersts` VALUES ('A', 1, 2, 3);
INSERT INTO `Greatersts` VALUES ('B', 5, 5, 2);
INSERT INTO `Greatersts` VALUES ('C', 4, 7, 1);
INSERT INTO `Greatersts` VALUES ('D', 3, 3, 6);
賦予行號實現語句
使用自定義變量
解法一 使用SET定義變量
SET @row_num:=0;
SELECT (@row_num:=@row_num+1) AS row_num, a.*
FROM Greatersts AS a;
解法二 INNER JOIN
SELECT (@row_num:=@row_num+1) AS row_num, a.*
FROM Greatersts AS a
INNER JOIN (SELECT @row_num:=0) b;
解法三
SELECT (@row_num:=@row_num+1) AS row_num, a.*
FROM Greatersts AS a, (SELECT @row_num:=0) b;
不使用自定義變量
解法四 使用子查詢
SELECT (SELECT COUNT()+1 FROM Greatersts AS b WHERE b.
key
< a.key
) AS row_num , a.
FROM Greatersts AS a;
查詢結果
Python重置MySQL的數據庫序號
重置gl00501表中id列的序號,使之連續
conn=py.connect(host='localhost',port=3306,user='root',passwd='XXX',db=table_name)
cur=conn.cursor()
sql1='set @i=0;'
sql2='update %s set id=(@i:=@i+1);'% db_name
sql3='alter table %s auto_increment =0;'% db_name
cur.execute(sql1)
cur.execute(sql2)
cur.execute(sql3)
cur.close()
conn.close()
參考文獻
1.Create a Cumulative Sum Column in MySQL
2.https://blog.csdn.net/zhou16333/article/details/104703394/