Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
652 views
in Technique[技术] by (71.8m points)

mysql - Two autoincrements columns or autoincrement and same value in other column

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...