Left JOIN faster or Inner Join faster?

后端 未结 4 1971
不思量自难忘°
不思量自难忘° 2021-01-02 03:06

So... which one is faster (NULl value is not an issue), and are indexed.

SELECT * FROM A
  JOIN B b ON b.id = a.id
  JOIN C c ON c.id = b.id 
 WHERE A.id = \         


        
4条回答
  •  心在旅途
    2021-01-02 03:32

    It depends; run them both to find out; then run an 'explain select' for an explanation.

    The actual performance difference may range from "virtually non-existent" to "pretty significant" depending on how many rows in A with id='12345' have no matching records in B and C.

    Update (based on posted query plans)

    When you use INNER JOIN it doesn't matter (results-wise, not performance-wise) which table to start with, so optimizer tries to pick the one it thinks would perform best. It seems you have indexes on all appropriate PK / FK columns and you either don't have an index on friend_events.userid or there are too many records with userid = '13006' and it's not being used; either way optimizer picks the table with less rows as "base" - in this case it's zcms_users.

    When you use LEFT JOIN it does matter (results-wise) which table to start with; thus friend_events is picked. Now why it takes less time that way I'm not quite sure; I'm guessing friend_events.userid condition helps. If you were to add an index (is it really varchar, btw? not numeric?) on that, your INNER JOIN might behave differently (and become faster) as well.

提交回复
热议问题