Auto generate serial numbers

前端 未结 2 682
南笙
南笙 2021-01-29 11:58

I wrote the count code below with the aim of having it produce auto-serial numbers for my data in place of the MySQL serial number which goes once the row is deleted. But when I

2条回答
  •  不知归路
    2021-01-29 12:30

    You need to configure your MySQL table so that the sn column has AUTO_INCREMENT enabled. Consider this example from the MySQL 5.0 Reference on AUTO_INCREMENT:

    CREATE TABLE animals (
     id MEDIUMINT NOT NULL AUTO_INCREMENT,
     name CHAR(30) NOT NULL,
     PRIMARY KEY (id)
    ) ENGINE=MyISAM;
    
    INSERT INTO animals (name) VALUES
     ('dog'),('cat'),('penguin'),
     ('lax'),('whale'),('ostrich');
    
    SELECT * FROM animals;
    

    Returns:

    +----+---------+
    | id | name    |
    +----+---------+
    |  1 | dog     |
    |  2 | cat     |
    |  3 | penguin |
    |  4 | lax     |
    |  5 | whale   |
    |  6 | ostrich |
    +----+---------+
    

    In this example, nothing was passed as id, but the result was automatically generated.

    You should define something link this for the sn column in your table.

    Edit: Assuming you absolutely must feel like you have an additional, offset, incrementing column, one option is to make it appear so when you query the table. In the example above, let's say we want an additional column, sn, and that the difference between id and sn is 7. We could do the following:

    SELECT *, (`id` + 7) as `sn` FROM animals;
    

    Returns:

    +----+---------+----+
    | id | name    | sn |
    +----+---------+----+
    |  1 | dog     |  8 |
    |  2 | cat     |  9 |
    |  3 | penguin | 10 |
    |  4 | lax     | 11 |
    |  5 | whale   | 12 |
    |  6 | ostrich | 13 |
    +----+---------+----+
    

    Note that although you can use sn in JOINs and other statements, you won't be able to use it as a foreign key in other tables.

提交回复
热议问题