美文网首页
使用分页插件SQL中,子查询的坑

使用分页插件SQL中,子查询的坑

作者: 燃英 | 来源:发表于2019-08-02 17:06 被阅读0次

    用Mybaits分页插件一时爽,一直用一直爽。 但是需要注意的是,很多分页插件的原理是将执行的SQL包装一层,然后再 count,在SQL中有子查询并且数据量多的情况下就会出现问题。

    我举一个实际开发中的例如:
    查询物料的分页列表,本来一条语句飞快

    SELECT t.`code`,t.`name` FROM t_material t;
    

    整合进Mybatis 分页插件后,debug 出来的SQL语句大致是:

    SELECT t.`code`,t.`name` FROM t_material t limit 10;
    

    另外加一个count (自动拦截生成)

    [http-apr-8889-exec-5] DEBUG c.d.d.m.paginator.support.SQLHelper - Total count SQL [select count(1) from (select
         t.`code`,t.`name`
        from
          t_material t
         ) tmp_count] 
    

    此时,需要改一个需求,每个物料所包含的附件个数

    OK,上来就是一个子查询

    SELECT
        t.`code`,
        t.`name`,
        (SELECT count(1) FROM t_material_attachment where code = t.code) as attachment_amount
    FROM
        tk3cloud_material t;
    

    依旧很快。

    再看一下分页生成的count

    [http-apr-8889-exec-6] DEBUG c.d.d.m.paginator.support.SQLHelper - Total count SQL [select count(1) from (select
        t.`code`,
        t.`name`,
        (SELECT count(1) FROM t_material_attachment where code = t.code) as attachment_amount
        from
          t_material t
         ) tmp_count] 
    

    但是数据量越来越多后就有问题了 ,出问题了。
    如果 t_material 里面有10W条记录,也意味着这个SQL会count 10W次,速度可想而知。

    如何优化?
    这种一对多的情况,不好 join , 我推荐用 Mybatis 的 collection 标签,把它提到SQL外面执行。

    相关文章

      网友评论

          本文标题:使用分页插件SQL中,子查询的坑

          本文链接:https://www.haomeiwen.com/subject/owaldctx.html