Mysql 数据库索引

Summary: Author: 张亚飞 | Read Time: 1 minute read | Published: 2018-06-13
Filed under Categories: LinuxTags: Note,

##

mysql分库分表、分区(partition)和主流中间件小讲

MySQL索引原理及慢查询优化

Mysql每次只用一个索引

select count(1) from table1 where column1 = 1 and column2 = 'foo' and column3 = 'bar'

以上应该用联合索引 index(column1,column2,column3)

数据库中查询记录时是否每次只能使用一个索引?

mysql 字段 null 与索引

建立一个不可为空的表 table1

DROP TABLE IF EXISTS `table1`;
CREATE TABLE table1
(
    `id`   INT(11)     NOT NULL,
    `name` varchar(20) NOT NULL
);

建立一个可为空的表 table2

DROP TABLE IF EXISTS `table2`;
CREATE TABLE table2
(
    `id`   INT(11)     NOT NULL,
    `name` varchar(20) NULL
);

向表 table1 插入测试数据:

INSERT INTO table1(`id`, `name`)
VALUES (4, 'zhaoyun'),
       (2, 'zhangfei'),
       (3, 'liubei');

向表 table2 插入测试数据:

INSERT INTO table2(`id`, `name`)
VALUES (1, 'zhaoyun'),
       (2, null);
  1. NOT IN子查询在有NULL值的情况下返回永远为空结果,查询容易出错
select name from table1 where name not in (select name from table2 where id != 1);
  1. 如果在两个字段进行拼接:首先要各字段进行非null判断,否则只要任意一个字段为空都会造成拼接的结果为null
select CONCAT('1', null) from table1;

– 执行结果为null。

  1. 如果有 Null column 存在的情况下,count(Null column)需要格外注意,null 值不会参与统计。
select count(name) from table1;
select count(name) from table2;
  1. 索引长度对比: Null 列需要更多的存储空间:需要一个额外字节作为判断是否为 NULL 的标志位
alter table table1 add index idx_name (name);
alter table table2 add index idx_name (name);
explain select * from table1 where name = 'zhaoyun';
explain select * from table2 where name = 'zhaoyun';

Comments

Cor-Ethan, the beverage → www.iirii.com