match_fields.md 941 字节
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 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
# 左匹配

Goods 表结构如下:

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

Joe 发现有大量查询 `select id, category_id, name, price from goods where name=? and category_id=?`
性能很差,应该如何优化?

## 答案

将该查询改写为 

```mysql
select id, category_id, name, price from goods where category_id=? and name=?;
```

## 选项

### A

将该查询改写为

```mysql
select id, category_id, name, price from goods where category_id and name= (?, ?);
```

### B

将该查询改写为

```mysql
select id, category_id, name, price from goods where not (category_id !=? or name != ?);
```

### C

将该查询改写为

```mysql
select id, category_id, name, price from goods where not (category_id !=?) and not (name != ?);
```