match_fields.md 1.2 KB
Newer Older
M
index  
Mars Liu 已提交
1 2 3 4
# 左匹配

Goods 表结构如下:

fix bug  
张志晨 已提交
5
```sql
M
index  
Mars Liu 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19
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/>

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 30
## 答案

将该查询改写为 

fix bug  
张志晨 已提交
31
```sql
M
index  
Mars Liu 已提交
32 33 34 35 36 37 38 39 40
select id, category_id, name, price from goods where category_id=? and name=?;
```

## 选项

### A

将该查询改写为

fix bug  
张志晨 已提交
41
```sql
M
index  
Mars Liu 已提交
42 43 44 45 46 47 48
select id, category_id, name, price from goods where category_id and name= (?, ?);
```

### B

将该查询改写为

fix bug  
张志晨 已提交
49
```sql
M
index  
Mars Liu 已提交
50 51 52 53 54 55 56
select id, category_id, name, price from goods where not (category_id !=? or name != ?);
```

### C

将该查询改写为

fix bug  
张志晨 已提交
57
```sql
M
index  
Mars Liu 已提交
58 59 60
select id, category_id, name, price from goods where not (category_id !=?) and not (name != ?);
```