金融量化AI研究--Claude, Python

这里用来记录一些本人运用Claude编程的心得或笔记

导航

MySQL-给一列赋予行号


现有一张表: 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/

posted on 2020-08-12 19:48  chengjon  阅读(1019)  评论(0)    收藏  举报