Left Join outperforming Inner Join?

后端 未结 6 1978
不思量自难忘°
不思量自难忘° 2021-01-01 19:56

I\'ve been profiling some queries in an application I\'m working on, and I came across a query that was retrieving more rows than necessary, the result set being trimmed dow

6条回答
  •  渐次进展
    2021-01-01 20:02

    Try this:

    SELECT `contacts`.*, `lists`.`name` AS `group`, `lists`.`id` AS `group_id`, `lists`.`shared_yn`, `tags`.`name` AS `context`, `tags`.`id` AS `context_id`, `tags`.`color` AS `context_color`, `users`.`id` AS `user_id`, `users`.`avatar` 
    FROM `contacts`  
    INNER JOIN `users` ON contacts.user_id='1' AND users.email=contacts.email
    LEFT JOIN `lists` ON lists.id=contacts.list_id  
    LEFT JOIN `lists_to_users` ON lists_to_users.user_id='1' AND lists_to_users.creator='1' AND lists_to_users.list_id=lists.id
    LEFT JOIN `tags` ON tags.id=lists_to_users.tag_id 
    ORDER BY `contacts`.`name` ASC
    

    That should give you an extra performance because:

    • You put all the inner joins before any "left" or "right" join appears. This filters out some records before applying the subsequent outer joins
    • The short-circuit of the "AND" operators (order of the "AND" matters). If the comparition between the columns and the literals is false, it won't execute the required table scan for the comparition between the tables PKs and FKs

    If you don't find any performance improvement, then replace all the columnset for a "COUNT(*)" and do your left/inner tests. This way, regardless of the query, you will retrieve only 1 single row with 1 single column (the count), so you can discard that the number of returned bytes is the cause of the slowness of your query:

    SELECT COUNT(*)
    FROM `contacts`  
    INNER JOIN `users` ON contacts.user_id='1' AND users.email=contacts.email
    LEFT JOIN `lists` ON lists.id=contacts.list_id  
    LEFT JOIN `lists_to_users` ON lists_to_users.user_id='1' AND lists_to_users.creator='1' AND lists_to_users.list_id=lists.id
    LEFT JOIN `tags` ON tags.id=lists_to_users.tag_id 
    

    Good luck

提交回复
热议问题