首先我们简单描述下

1. 表关系

bs_item_reality 和 bs_item_standard_dictionary 的关系是
多个 sxunid 的 dirUnid 为同一个,也就是对应一个 bs_item_standard_dictionary 表的 dirUnid
2. 表数据以及索引
bs_item_reality 表数据有 401085
表索引:
sxunid 主键
areaname 普通索引
dirUnid 普通索引

bs_item_standard_dictionary 表 7547

3. 查看原始的SQL

select DISTINCT a.sxunid from bs_item_reality a inner join bs_item_standard_dictionary b on a.dirUnid = b.unid WHERE b.unid in ( '0C5E9744F654A26D39254DC5E78C38AA' ) and a.sxunid not in ( 'E822DE265B80981A8FB5F2B19D067E58' ) limit 10

3.1 这里直接使用Navicat 查询 5次的时间

序号查询时间(s)
10.459
20.548
30.361
40.358
50.354

image.png

3.2 explain 的执行计划

image.png
image.png
从图上可以 type 基本都为 const、range;Key 也都是主键索引;Extra 也没有 Using filesort 和 Using temporary,注意 rows 这里

4. 尝试第一次优化

优化后的sql

select DISTINCT a.sxunid from  bs_item_standard_dictionary b inner join bs_item_reality a    on  b.unid=a.dirUnid WHERE 1=1 and a.sxunid not in ( 'E822DE265B80981A8FB5F2B19D067E58' )  and  a.dirUnid in ( '0C5E9744F654A26D39254DC5E78C38AA' ) limit 10

4.1 这里直接使用Navicat 查询 5次的时间

序号查询时间(s)
10.102
20.103
30.102
40.104
50.102

image.png

4.2 explain 的执行计划

image.png
image.png

5.第二次优化
优化后的sql

select DISTINCT a.sxunid from  bs_item_standard_dictionary b inner join bs_item_reality a    on  a.dirUnid = b.unid WHERE 1=1 and a.sxunid not in ( 'E822DE265B80981A8FB5F2B19D067E58' )  and  b.unid in ( '0C5E9744F654A26D39254DC5E78C38AA' ) limit 10

5.1 这里直接使用Navicat 查询 5次的时间

序号查询时间(s)
10.102
20.103
30.102
40.104
50.102

image.png

5.2 explain 的执行计划

image.png
image.png