欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mysql 对已有数据的表换主键及主键初始化赋值

程序员文章站 2024-03-09 10:00:29
...

顺序执行以下sql语句
1.删除表主键约束

ALTER TABLE ba_shop DROP PRIMARY KEY;

2.添加新主键字段id

ALTER TABLE ba_shop ADD id BIGINT(20) NOT NULL COMMENT ‘主键’ FIRST;

3.id赋值

#显示行号的sql
SELECT
@r := @r + 1 AS row_num,a.*
FROM ba_shop a, (SELECT @r := 0) b;

4.把已经存在的行号当作主键赋值给主键

UPDATE ba_shop bs1
INNER JOIN (
	SELECT
		@r := @r + 1 AS row_num,
		bs2.shop_id
	FROM
		ba_shop bs2,
		(SELECT @r := 0) b
) tb ON bs1.shop_id = tb.shop_id
SET bs1.id = tb.row_num;

5.设置主键

ALTER TABLE ba_shop
  ADD PRIMARY KEY (`id`);