Two autoincrements columns or autoincrement and same value in other column

后端 未结 3 1609
情深已故
情深已故 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:37

    So you want to let one column use the auto_increment feature, but make another column in the same table also have the same value?

    I can't think of a reason you would need this feature. Perhaps you could explain what you're trying to accomplish, and I can suggest a different solution?

    A trigger won't work for this. It's a chicken-and-egg problem:

    • You can't change any column's value in an AFTER trigger.
    • But the auto-increment value isn't set yet when a BEFORE trigger executes.

    It also won't work to use a MySQL 5.7 GENERATED column:

    CREATE TABLE MyTable (
      id INT AUTO_INCREMENT PRIMARY KEY,
      why_would_you_want_this INT GENERATED ALWAYS AS (id)
    );
    
    ERROR 3109 (HY000): Generated column 'why_would_you_want_this' 
    cannot refer to auto-increment column.
    

    You can't do it in a single SQL statement. You have to INSERT the row, and then immediately do an UPDATE to set your second column to the same value.

    CREATE TABLE MyTable (
      id INT AUTO_INCREMENT PRIMARY KEY,
      why_would_you_want_this INT
    );
    
    INSERT INTO MyTable () VALUES ();
    
    UPDATE MyTable SET why_would_you_want_this = LAST_INSERT_ID() 
    WHERE id = LAST_INSERT_ID();
    

    You could alternatively generate the ID value using some other mechanism besides AUTO_INCREMENT (for example a Memcached incrementing key). Then you could insert the new value in both columns:

    INSERT INTO MyTable (id, why_would_you_want_this) VALUES ($gen_id, $gen_id);
    

提交回复
热议问题