Mysql 数据库表中如何插入行号

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

      

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值