match_fields.md 1.2 KB
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,
    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=?`
性能很差,应该如何优化?

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

M
Mars Liu 已提交
22
点击进入[MySQL实战练习环境](https://mydev.csdn.net/product/pod/new?image=cimg-centos7-skilltreemysql&connect=auto&create=auto&utm_source=skill)
M
Mars Liu 已提交
23 24
* `show databases` 列出所有数据库
* `show tables` 列出所有表
M
Mars Liu 已提交
25

M
index  
Mars Liu 已提交
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 54 55 56 57 58 59
## 答案

将该查询改写为 

```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 != ?);
```