mysql 想必大家都不陌生,但它并没有Oracle那么强大的处理row_number这样的函数,那么如何实现行号的添加的,可以考虑使用如下的三种方式:
1. 增加临时表(select @rownum:=0)
select @rownum:=@rownum+1 as rowid,
a.*
from (select * from t) a ,(select @rownum:=0)
这种方式也是网上搜索后常用的方式.
2. 使用自增.
在建表的时候,会有这个提示,在第一个字段rowid上勾选上它就可以了 .
3. 使用存储过程的方式实现.
3.1 建表sequence
CREATE TABLE `sequence` (
`seq_name` varchar(50) NOT NULL,
`current_val` int(11) NOT NULL,
`increment_val` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`seq_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
如果你要操作的目标表表名是student ,那么首先执行insert into sequence(seq_name,current_val,increment_val) values('student',0,1)
3.2创建如下的两个store procedure,类型function
`func_get_currentId_from_tableName`(tableName VARCHAR(50)) RETURNS int(11)
begin
declare value integer;
set value = 0;
select current_val into value from sequence where seq_name = tableName;
return value;
end
`func_get_nextId_from_TableName`(tableName varchar(50)) RETURNS int(11)
begin
update sequence set current_val = current_val + increment_val where seq_name = tableName ;
return func_get_currentId_from_tableName(tableName);
end
3.3 执行
执行插入目标表的操作
insert into student(rowid,column_name1,column_name2...)
select func_get_nextId_from_TableName('student') as rowid, column_name1,column2.... from tablename