combinate.md 759 字节
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 20 21 22
# 组合索引

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 应该如何优化?

## 答案

```mysql
M
Mars Liu 已提交
23
alter table goods add index (`stock-id`, category_id, name);
M
index  
Mars Liu 已提交
24 25 26 27 28 29 30
```

## 选项

### A

```mysql
M
Mars Liu 已提交
31
alter table goods add index (`stock-id` and category_id and name);
M
index  
Mars Liu 已提交
32 33 34 35 36 37 38 39 40 41 42
```

### B

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

### C

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