关于mysql:如何更改表的默认排序规则?

How to change the default collation of a table?

1
create table check2(f1 varchar(20),f2 varchar(20));

使用默认排序规则latin1_general_ci创建表;

1
2
alter table check2 collate latin1_general_cs;
show full columns from check2;

将各列的排序规则显示为"Latin1_General_Ci"。

那么alter table命令的效果是什么呢?


要更改包括现有列在内的表的默认字符集和排序规则(请注意convert to子句):

1
alter table <some_table> convert to character set utf8mb4 collate utf8mb4_unicode_ci;

由于一些评论的提示,编辑了答案:

Should avoid recommending utf8. It's almost never what you want, and often leads to unexpected messes. The utf8 character set is not fully compatible with UTF-8. The utf8mb4 character set is what you want if you want UTF-8. – Rich Remer Mar 28 '18 at 23:41

That seems quite important, glad I read the comments and thanks @RichRemer . Nikki , I think you should edit that in your answer considering how many views this gets. See here https://dev.mysql.com/doc/refman/8.0/en/charset-unicode-utf8.html and here What is the difference between utf8mb4 and utf8 charsets in MySQL? – Paulpro Mar 12 at 17:46


MySQL有4个排序规则级别:服务器、数据库、表、列。如果更改服务器、数据库或表的排序规则,则不会更改每列的设置,但会更改默认排序规则。

例如,如果更改数据库的默认排序规则,则在该数据库中创建的每个新表都将使用该排序规则;如果更改表的默认排序规则,则在该表中创建的每个列都将获得该排序规则。


它为表设置默认的排序规则;如果您创建一个新列,它应该与拉丁语"常规"进行排序,我想。尝试为单个列指定排序规则,看看是否有效。MySQL在处理这个问题的方式上有一些非常奇怪的行为。


可能需要更改架构而不仅仅是表

1
ALTER SCHEMA `<database name>`  DEFAULT CHARACTER SET utf8mb4  DEFAULT COLLATE utf8mb4_unicode_ci (as Rich said - utf8mb4);

(玛丽亚德10)