Two autoincrements columns or autoincrement and same value in other column

后端 未结 3 1601
情深已故
情深已故 2020-12-22 12:47

I need two columns in table that would have same value on insert. Is there any way to do it from database side?

3条回答
  •  甜味超标
    2020-12-22 13:36

    You can do this in one query by using the primary key (assumed to be id) and setting your column (assumed to be columnName):

    "INSERT INTO tableName SET `columnName` = (SELECT MAX(x.id) FROM tableName x)+1"
    

    This will not work if you have deleted the most recent primary key row however. To get past this, you can insert into the id as well:

    "INSERT INTO tableName SET `columnName` = (SELECT MAX(x.id) FROM tableName x)+1, `id`= (SELECT MAX(x.id) FROM tableName x)+1" 
    

    However, this solution has the downside (or upside depending on the case) of reusing primary key values that have already been deleted.

    suggested way:
    To use the actual auto_increment value, you can do this:

    "INSERT INTO tableName SET `columnName` = (SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'db_name' AND TABLE_NAME = 'table_name')"
    

    Sources that helped me solve this:
    Prashant Pimpale's answer

提交回复
热议问题