mysql 指定一列自动递增,手动自动递增一列MySQL

I have a table with columns:

[id,name,public_id]

actually the table contains

[1,john,0]

[2,sara,0]

[3,jack,0]

.....

I want to change the third column to 1050,1051,1052....

[1,john,1050]

[2,sara,1051]

[3,jack,1052]

.....

How can I make that update?

Some considerations: The public id must be over 1049 and must be consecutive. For example for 100 rows the public_id must be [1050....1149]

Thanks in advance

解决方案

Assuming your table's name is TEST_TABLE, this MySQL syntax will update PUBLIC_ID with consecutive values starting from 1500 (and in order of ID):

REPLACE INTO TEST_TABLE

SELECT TEST_TABLE.ID, TEST_TABLE.NAME, @ROWNUM := @ROWNUM + 1

FROM

TEST_TABLE,

(SELECT @rownum := 1499) R

ORDER BY ID

In plain English:

For each row, figure out its order when data is sorted by ID. Call this order "ROWNUM".

Put ROWNUM (+ starting offset) back to the table instead of the original PUBLIC_ID.

WARNING: According to MySQL documentation, REPLACE will actually delete a duplicated row before inserting it again (instead of just updating modified fields), which my be an issue in the presence of foreign keys.

(Not sure about SQLite, but I'm guessing you could employ a similar general idea.)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值