combinate.md 1017 字节
Newer Older
M
index  
Mars Liu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# 组合索引

Goods 表结构如下:

```mysql
create table goods(
    id int primary key auto_increment,
    category_id int,
    category varchar(64),
    name varchar(256),
    price decimal(12, 4),
    stock int,
    upper_time timestamp
)
```

现有大量查询 `select id, category_id, name, price, stock from goods where stock=? and category_id=? and name like ?`
Joe 应该如何优化?

M
Mars Liu 已提交
20 21
<hr/>

F
feilong 已提交
22
点击进入[MySQL实战练习环境](https://mydev.csdn.net/product/pod/new?image=cimg-centos7-skilltreemysql&connect=auto&create=auto&utm_source=skill){target="_blank"}。
F
feilong 已提交
23

F
feilong 已提交
24 25
* `show databases;` 列出所有数据库
* `show tables;` 列出所有表
M
Mars Liu 已提交
26

M
index  
Mars Liu 已提交
27 28 29
## 答案

```mysql
M
Mars Liu 已提交
30
alter table goods add index (`stock-id`, category_id, name);
M
index  
Mars Liu 已提交
31 32 33 34 35 36 37
```

## 选项

### A

```mysql
M
Mars Liu 已提交
38
alter table goods add index (`stock-id` and category_id and name);
M
index  
Mars Liu 已提交
39 40 41 42 43 44 45 46 47 48 49
```

### B

```mysql
alter table goods add index (concat(stock, category_id, name));
```

### C

```mysql
M
Mars Liu 已提交
50
alter table goods add index (`stock-id` + category_id + name);
M
index  
Mars Liu 已提交
51
```