mysql 中LIKE 与FIND_IN_SET 与关联表left join 速度效率比较

有一张表Table有IDStr字段,如下只显示二个字段还有很多其他字段

方式一 字段逗号分割,直接用UserIDStr字段,里面存多个ID用逗号分割

UUID  UserIDStr

1111  1,2,3

2222  3

方式二用关联表,关联表如下:

UUID  UserID

1111   1

1111   2

1111   3

222   3

 

测试了50W条数量

-- 方式一设计用 Like查几次时间分别是: 1.192s 1.140s 1.171s 1.425s
select * from af_archive where concat(',',EditUserIDArr,',') like CONCAT('%,','6',',%') and CreateUserID=10 order by CreateTime desc limit 11,20;

-- 方式一设计用 FIND_IN_SET查了几次时间分别是: 1.441s 1.336s 1.214s 1.116s
select * from af_archive where FIND_IN_SET('6',EditUserIDArr) and CreateUserID=10 order by CreateTime desc limit 11,20;

--方式二设计用 left join on 查了几次时间分别是 1.134s 1.037s 1.068s 1.120s 1.112s 1.472 1.422 1.160s 1.047
select a.* from af_archive a left join archiveedituser b on a.ArchiveUUID=b.ArchiveUUID and b.EditUserID=6 where a.CreateUserID=10 order by a.CreateTime desc limit 11,20;

分析结果

方式一(字段逗号分割)的LIKE与FIND_IN_SET时间差不多,不分上下

方式二(关联表)的用LEFT JOIN ON 时间比上面这种方式要快一些。

另外方式二有二种 不推荐的写法查询时间较久,如下

--方式二先 left join on再 where条件 用时 5.641s 5.488s 7.679s 6.230
select a.* from af_archive a left join archiveedituser b on a.ArchiveUUID=b.ArchiveUUID where b.EditUserID=6 and a.CreateUserID=10 order by a.CreateTime desc limit 11,20;

-- 方式二用where in 用时: 6.397s 5.842s 5.621s
select a.* from af_archive a where 6 in (select b.EditUserID from archiveedituser b where a.ArchiveUUID=b.ArchiveUUID) and a.CreateUserID=10 order by a.CreateTime desc limit 11,20;

=================================

后面把数据添加到150W条数据测试结果如下

-- Like 7.256s 6.072s 8.108s 6.013s 6.060s
-- select * from jsj_af.af_archive where concat(',',EditUserIDArr,',') like CONCAT('%,','6',',%') and CreateUserID=10 order by CreateTime desc limit 11,20;

-- FIND_IN_SET 5.624s 5.574s 5.608s 7.465s 5.931s
-- select * from jsj_af.af_archive where FIND_IN_SET('6',EditUserIDArr) and CreateUserID=10 order by CreateTime desc limit 11,20;

-- left join on 5.872s 7.254s 7.317s 5.671s 6.305s
-- select a.* from jsj_af.af_archive a left join jsj_af.archiveedituser b on a.ArchiveUUID=b.ArchiveUUID and b.EditUserID=6 where a.CreateUserID=10 order by a.CreateTime desc limit 11,20;

posted @ 2020-02-27 18:28  为乐而来  阅读(3932)  评论(1编辑  收藏  举报