【MySQL】MySQL使用小坑汇总

51 阅读2分钟

MySQL使用默认方式建表会存在部分预期之外的查询结果,为避免此类问题的发生,特在此汇总。。

1. 查询条件默认不区分大小写

-- 初始化
drop table if  exists test;
create table test(
id int primary key  auto_increment,
name varchar(256),
addr varchar(256)
);

insert into test(name,addr) values('AA','  河北省   ');
insert into test(name,addr) values('aa','北京市   ');

查询SQLselect * from test where name = 'aa';

image.png 原因:mysql默认建表的collate为:utf8mb4_general_ci,其中ci表示不区分大小写,如果需要查询需要区分大小写,可以使用如下方案。

-- 方法1:查询时字段标记为binary
select * from test where binary name = 'aa';
-- 方法2:增加字段的collate为bin模式
drop table if  exists test;
create table test(
id int primary key  auto_increment,
name varchar(256) binary ,
addr varchar(256)
);

-- 方法3:修改表的collate模式为bin模式
drop table if  exists test;
create table test(
id int primary key  auto_increment,
name varchar(256)  ,
addr varchar(256)
) collate = utf8mb4_bin;

2. 自动trim字段后面的空格进行数据比较

-- 初始化
drop table if  exists test;
create table test(
id int primary key  auto_increment,
name varchar(256),
addr varchar(256)
);

insert into test(name,addr) values('AA','  河北省   ');
insert into test(name,addr) values('aa','北京市   ');

查询SQL:select * from test where addr = '河北省';

image.png

查询SQL:select * from test where addr = '北京市';

image.png

3. MySQL创建索引时,索引存在长度限制

源:https://dev.mysql.com/doc/refman/8.4/en/column-indexes.html

Prefixes can be up to 767 bytes long for `InnoDB` tables that use the `REDUNDANT` or `COMPACT` row format. The prefix length limit is 3072 bytes for `InnoDB` tables that use the `DYNAMIC` or `COMPRESSED` row format.
drop table if exists test;
create table test(
id int primary key  auto_increment,
name varchar(768),
addr varchar(769)
);

create index idx1 on  test(name);
create index idx2 on test(addr);

在使用innodb引擎并且使用utf8mb4编码的情况下,单个索引的最大长度为:3072/4=768,所以上面两条索引执行时,第一条可以执行成功,第二条报如下错误:1071 - Specified key was too long; max key length is 3072 bytes, 这就是有MySQL中对索引长度的限制,使用时需要注意。

4. 分组查询时千万不要忘记group by

-- 初始化
drop table if exists test;
create table test(
id int primary key auto_increment,
name varchar(256),
addr varchar(256)
);
insert into test(name,addr) values('AA',' 河北省 ');
insert into test(name,addr) values('aa','北京市 ');
insert into test(name,addr) values('bb','河北省');
-- 问题SQL级说明
select name,count(*)
from test
-- group by name;

在MySQL中,存在分组函数时不写group by不会报错,但是查询结果只有一条,相当于分组后的第一条结果。所以针对于分组函数一定要注意。