Is it better to use INNER JOIN or EXISTS to find belonging to several in m2m relation?

前端 未结 4 1480
清歌不尽
清歌不尽 2021-02-18 15:03

Given m2m relation: items-categories I have three tables:

  • items,
  • categories and
  • ite
4条回答
  •  终归单人心
    2021-02-18 15:37

     select distinct `user_posts_id` from `user_posts_boxes`
         where `user_id` = 5 
         and 
         exists (select * from `box` where `user_posts_boxes`.`box_id` = `box`.`id` 
         and `status` in ("A","F"))
         order by `user_posts_id` desc limit 200;
    
    
    
     select distinct `user_posts_id` from `user_posts_boxes`
     INNER JOIN box on box.id = `user_posts_boxes`.`box_id` and box.`status` in ("A","F")
     and box.user_id = 5
     order by `user_posts_id` desc limit 200
    

    I tried with both query, But above query works faster for me.Both tables having large dataset. Almost "user_posts_boxes" has 4 million and boxes are 1.5 million.

    First query took = 0.147 ms 2nd Query almost = 0.5 to 0.9 MS

    But my database tables are inno db and having physical relationships are also applied.

    SO I should go for exists but it also depends upon how you have your db structure.

提交回复
热议问题