简体   繁体   中英

Changing an enum type in mysql

I'm working with a mysql database table that stores a 6 bit value as an enum. Only 20 or so of the values were specified, with the remainder having names like "type_30". I'm now changing the column to add descriptive text to some of the values using alter TABLE table_name modify COLUMN column_name enum( 'text', ... ); The table is not all that big (about 13e6 rows), but the alter command has been running for quite some time now. I'm a bit surprised, since it would seem that changing the enumeration type should only require modifying metadata for the table (so the number of rows in the table should be irrelevant.)

Why does the number of rows in the column matter for this type of operation? Is there a simple way for me to quickly change the labels of the enum?

From MySQL documentation :

Changing the definition of an ENUM or SET column by adding new enumeration or set members to the end of the list of valid member values, as long as the storage side of the data type does not change. For example, adding a member to a SET column that has 8 members changes the required storage per value from 1 byte to 2 bytes; this will require a table copy. Adding members in the middle of the list causes renumbering of existing members, which requires a table copy.

Enums are stored as an integer. For example, if your enum was ('yes', 'no), 'yes' will be 1 and 'no' will be 2.

Inserting new items in the middle requires renumbering, so MySQL will create a new table and copy rows over to change the data. It's not simply a change to the metadata.

There is no quick way to change the existing labels, since it affects the data. However, if you only add values to the end of the enum, only a metadata change is required.

There is no simple way to quickly change the labels for an enum column. Running MODIFY COLUMN like you did is not updating the labels, it's actually trying to remap all of the existing data to fit your updated enum values.

For example, if your column was ENUM('blue','red','yellow') before then you would have the following index values:

1 = blue
2 = red
3 = yellow

If you ran alter TABLE table_name modify COLUMN column_name enum( 'red','yellow','blue' ); it would update the index values as follows:

1 = red
2 = yellow
3 = blue

Which is what you want. But it would also go back and update all of the existing rows of the table to remap the index values:

1 -> 3
2 -> 1
3 -> 2

Which you do not want.

If you simply want to update the labels without modifying the existing row data, then you will need to modify the FRM file. Here's one description of how to do that:

https://dba.stackexchange.com/questions/6547/can-i-rename-the-values-in-a-mysql-enum-column-in-one-query

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