1. MySQL 英文大小写不敏感的原因
通过 show character set 命令,你查看的到的
-
utf8 字符集的
Default collation是 utf8_general_ci 。 -
utf8mb4 字符集的
Default collation是 utf8mb4_general_ci 。
collation 这个设置关系到 MySQL 中的 “英文字符大小写不敏感” 问题。
::: tip
通过 show collation 命令,你可以查看到 MySQL 支持的所有的 collation 。
:::
这里的 _ci 指的是 Case Insensitive ,即 “大小写不敏感” 。a 和 A 会在字符判断中被当作一样。
例如,你执行 select * from department where name = 'testing' ,可能会出现以下两行数据:
| id | name | location |
|---|---|---|
| 1 | Testing | WuHan |
| 6 | testing | BeiJing |
2. 解决方案
2.1 解决方案一(治标)
治标的办法是在查询语句中使用 binary 关键字,binary 关键字可以加在两处地方(效果一样):
> select * from department where name = binary 'testing';
> select * from department where binary name = 'testing';
binary 表示的是:以字符串的二进制数据为依据进行比较,这样,比较的结果自然就是大小写敏感的。
2.2 解决方案二(治本)
在指定 Charset(utf8 或 utf8mb4)时,同时指定与之配套使用的 Collation 。
通过使用命令 show collation where Charset = '...' 可以查看 utf8 和 utf8mb4 对应的 Collation 。但是,可惜的是有 _ci,却没有 _cs<small>(Case Sensitive,大小写敏感)</small>的 Collation !
不过,有 utf8_bin 和 utf8mb4_bin 。
你可以在建库,或建表,或在列声明中使用它们。例如:
DROP DATABASE IF EXISTS scott;
CREATE DATABASE scott
DEFAULT CHARACTER SET utf8mb4 -- 乱码问题
DEFAULT COLLATE utf8mb4_bin -- 英文大小写不敏感问题
;
USE scott;










网友评论