简体   繁体   中英

Migrating Primary Key to use AUTO_Increment

I have a table where the primary key is sale_id, payment_type

mysql> describe phppos_sales_payments;
+----------------+---------------+------+-----+---------+-------+
| Field          | Type          | Null | Key | Default | Extra |
+----------------+---------------+------+-----+---------+-------+
| sale_id        | int(10)       | NO   | PRI | NULL    |       |
| payment_type   | varchar(255)  | NO   | PRI | NULL    |       |
| payment_amount | decimal(15,2) | NO   |     | NULL    |       |
+----------------+---------------+------+-----+---------+-------+

I want to add a new field id that is an auto increment. The reason for this is I want to track payments of the same type individually. Is it possible to do this without losing data?

This is how you can alter your table

ALTER TABLE `phppos_sales_payments`
  -- add a unique index based on the current primary key
  ADD UNIQUE (`sale_id`,`payment_type`), 
  -- drop the current primary key
  DROP PRIMARY KEY,
  -- add the new identity column with autoincrement
  ADD COLUMN `id` int(10) NOT NULL AUTO_INCREMENT FIRST,
  -- set primary key to the new identity column 
  ADD PRIMARY KEY (`id`);

The "magic" is to add an unique index, because foreign key must have an index and in second place add the new identity column with autoincrement and set the primary key for that column in one go.

SQL Fiddle DEMO

只需保留您的sale_id,payment_type密钥(而不是主密钥),然后添加一个id INT NOT NULL AUTO_INCREMENT并使其成为主密钥:不会丢失任何信息和新的主密钥。

You'll need to execute a single ALTER TABLE statement to achieve this:

ALTER TABLE `table` DROP PRIMARY KEY, 
ADD COLUMN id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST, 
ADD UNIQUE sale_id_payment_type( sale_id, payment_type );
 ALTER TABLE `table` DROP PRIMARY KEY,  

 ALTER TABLE `table` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT FIRST
 ALTER TABLE `table` ADD PRIMARY KEY (id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM