In what order are MySQL JOINs evaluated?

后端 未结 7 1356
情书的邮戳
情书的邮戳 2020-11-30 09:26

I have the following query:

SELECT c.*
FROM companies AS c
JOIN users AS u USING(companyid)
JOIN jobs AS j USING(userid)
JOIN useraccounts AS us USING(userid         


        
7条回答
  •  抹茶落季
    2020-11-30 10:11

    1) Using is not exactly the same as on, but it is short hand where both tables have a column with the same name you are joining on... see: http://www.java2s.com/Tutorial/MySQL/0100__Table-Join/ThekeywordUSINGcanbeusedasareplacementfortheONkeywordduringthetableJoins.htm

    It is more difficult to read in my opinion, so I'd go spelling out the joins.

    3) It is not clear from this query, but I would guess it does not.

    2) Assuming you are joining through the other tables (not all directly on companyies) the order in this query does matter... see comparisons below:

    Origional:

    SELECT c.* 
        FROM companies AS c 
        JOIN users AS u USING(companyid) 
        JOIN jobs AS j USING(userid) 
        JOIN useraccounts AS us USING(userid) 
    WHERE j.jobid = 123
    

    What I think it is likely suggesting:

    SELECT c.* 
        FROM companies AS c 
        JOIN users AS u on u.companyid = c.companyid
        JOIN jobs AS j on j.userid = u.userid
        JOIN useraccounts AS us on us.userid = u.userid 
    WHERE j.jobid = 123
    

    You could switch you lines joining jobs & usersaccounts here.

    What it would look like if everything joined on company:

    SELECT c.* 
        FROM companies AS c 
        JOIN users AS u on u.companyid = c.companyid
        JOIN jobs AS j on j.userid = c.userid
        JOIN useraccounts AS us on us.userid = c.userid
    WHERE j.jobid = 123
    

    This doesn't really make logical sense... unless each user has their own company.

    4.) The magic of sql is that you can only show certain columns but all of them are their for sorting and filtering...

    if you returned

    SELECT c.*, j.jobid....  
    

    you could clearly see what it was filtering on, but the database server doesn't care if you output a row or not for filtering.

提交回复
热议问题