Autoincrement manually a column MySQL

后端 未结 2 1322
余生分开走
余生分开走 2021-01-27 14:52

I have a table with columns:

[id,name,public_id]

actually the table contains

[1,john,0]
[2,sara,0]
[3,jack,0]
.....


        
相关标签:
2条回答
  • 2021-01-27 15:16

    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)
  • 2021-01-27 15:27

    You can do an update like this:

    UPDATE table SET public_id = id + 1049
    

    With this, you are using the ID, and adding 1049 to it to get the result you need

    0 讨论(0)
提交回复
热议问题