match_fields.md 1.3 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
32 33 34 35 36 37
select id, 
       category_id, 
       name, 
       price 
from goods 
where category_id=? and name=?;
M
index  
Mars Liu 已提交
38 39 40 41 42 43 44 45
```

## 选项

### A

将该查询改写为

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

### B

将该查询改写为

fix bug  
张志晨 已提交
59
```sql
60 61 62 63 64 65
select id, 
       category_id, 
       name, 
       price 
from goods 
where not (category_id !=? or name != ?);
M
index  
Mars Liu 已提交
66 67 68 69 70 71
```

### C

将该查询改写为

fix bug  
张志晨 已提交
72
```sql
73 74 75 76 77 78
select id, 
       category_id, 
       name, 
       price 
from goods 
where not (category_id !=?) and not (name != ?);
M
index  
Mars Liu 已提交
79 80
```