mysql 修改表、列的字符集和校對規則
將表的所有資料轉為另外一種字符集和校對規則
To change the table default character set and all character columns (CHAR
, VARCHAR
, TEXT
)
to a new character set, use a statement like this:
ALTER TABLE tbl_name
CONVERT TO CHARACTER SET charset_name
[COLLATE collation_name
];
The statement also changes the collation of all character columns. If you specify no COLLATE
For a column that has a data type of VARCHAR
or
one of the TEXT
types, CONVERT
TO CHARACTER SET
will change the data type as necessary to ensure that the new column is long enough to store as many characters as the original
column. For example, a TEXT
column
has two length bytes, which store the byte-length of values in the column, up to a maximum of 65,535. For a latin1
TEXT
column,
each character requires a single byte, so the column can store up to 65,535 characters. If the column is converted to utf8
,
each character might require up to three bytes, for a maximum possible length of 3 × 65,535 = 196,605 bytes. That length will not fit in a TEXT
column's
length bytes, so MySQL will convert the data type to MEDIUMTEXT
,
which is the smallest string type for which the length bytes can record a value of 196,605. Similarly, a VARCHAR
column
might be converted to MEDIUMTEXT
.
注意:
使用convert to character set charset_name,如果轉換後的資料型別不能儲存全部資料,會發生資料型別變化。
比如text最多可以儲存65535個位元組,latin1字符集下,一個字元佔用一個位元組,所以也就是65535個字元,轉換為utf8,一個字元至多可以佔用3個位元組,所以,最壞的情況,轉換後就需要65535*3個位元組,超出text容量,Mysql會自動將資料型別轉為mediumtext
修改某列的字符集
To avoid data type changes of the type just described, do not use CONVERT
TO CHARACTER SET
. Instead, use MODIFY
to change individual
columns. For example:
ALTER TABLE t MODIFY latin1_text_col TEXT CHARACTER SET utf8;
ALTER TABLE t MODIFY latin1_varchar_col VARCHAR(M
) CHARACTER SET utf8;
If you specify CONVERT TO CHARACTER
SET binary
, the CHAR
, VARCHAR
,
and TEXT
columns
are converted to their corresponding binary string types (BINARY
, VARBINARY
, BLOB
).
This means that the columns no longer will have a character set and a subsequent CONVERT
TO
operation will not apply to them.
If charset_name
is DEFAULT
,
the database character set is used.
修改某表的預設字符集和校對規則
只會對以後的列有影響,對已經建立的列,不會產生影響。
To change only the default character set for a table, use this statement:
ALTER TABLEtbl_name
DEFAULT CHARACTER SET charset_name [COLLATE collation_name]
;
參考