Mysql query with Left Join is too very slow

后端 未结 6 1173
萌比男神i
萌比男神i 2021-02-13 16:09

Query:

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

Both tabl

6条回答
  •  [愿得一人]
    2021-02-13 16:46

    Do you really need the != or is it meant to be =?

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

    This will select nearly the cartesian product of the 2 tables. (I guess around 60 million rows)

    Edit: From the comment

    yes it is " != " to match tbl_rls.id those are not in tblc_comment_manager

    I think this is what you need if you want to use the outer join approach.

     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
    

    Although my preference is usually

     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)
    

提交回复
热议问题