代码之家  ›  专栏  ›  技术社区  ›  Arshdeep

使用左连接的Mysql查询速度太慢

  •  7
  • Arshdeep  · 技术社区  · 14 年前

    查询:

       select `r`.`id` as `id` 
         from `tbl_rls` as `r` 
    left join `tblc_comment_manager` as `cm` on `cm`.`rlsc_id` != `r`.`id`
    

    两个表都有8k记录,但为什么速度很慢,有时需要2-3分钟甚至更多?

    所有建议索引列的人都是正确的。 是的,我写的问题是愚蠢和错误的。谢谢你纠正我。

    6 回复  |  直到 12 年前
        1
  •  26
  •   bpeterson76    14 年前

    还可以考虑为表编制索引。我们正在一个100万+记录表上运行多个左联接,返回结果所需时间不超过一两秒。

        2
  •  13
  •   Martin Smith    14 年前

    你真的需要这个吗 != = ?

     select `r`.`id` as `id` from `tbl_rls` as `r` 
      left join `tblc_comment_manager` as `cm` 
    on  `cm`.`rlsc_id`!=`r`.`id
    

    编辑: 从评论中

    是的,它是“!=”匹配tbl\U rls.id

    我想如果你想使用 outer join 接近。

     select DISTINCT `r`.`id` as `id` from `tbl_rls` as `r` 
      left join `tblc_comment_manager` as `cm` 
    on  `cm`.`rlsc_id`=`r`.`id
    WHERE `cm`.`rlsc_id` IS NULL
    

    虽然我的偏好是

     select `r`.`id` as `id` 
     from `tbl_rls`
     as `r` 
     WHERE NOT EXISTS(
              SELECT * FROM `tblc_comment_manager` as `cm` 
              WHERE  `cm`.`rlsc_id`=`r`.`id)
    
        3
  •  4
  •   Naktibalda    14 年前

    您要选择什么?

    select `r`.`id`
    from `tbl_rls` as `r` 
    left join `tblc_comment_manager` as `cm` 
        on  `cm`.`rlsc_id`=`r`.`id
    where `cm`.`rlsc_id` IS NULL
    
        4
  •  4
  •   middus    14 年前

    MySQL的 EXPLAIN

        5
  •  3
  •   JohnB    14 年前

    您可能需要提供更多信息。但有一件事我会尝试颠倒ON子句的顺序(因为它太简单了):

    ON r.id != cm.rlsc_id

    Edit:您应该在PK(id)列上放置索引。

    但我认为 this article might help you out .

    基本上是这么说的 NOT IN 占用的资源比 LEFT JOIN . 那篇文章的一位评论员提到 NOT EXISTS 是最好的。

    另外,我不确定这是否准确,但是 this article says that NOT IN does a full table scan, and NOT EXISTS can use an index .

        6
  •  1
  •   DaveWilliamson    14 年前

    选择 r . id 作为 身份证件
    tbl_rls r
    哪里 r . 不在(选择distinct) cm . rlsc_id tblc_comment_manager 厘米