WHERE clause before INNER JOIN

后端 未结 7 842
小蘑菇
小蘑菇 2020-12-13 13:16

If I have

SELECT * FROM Table1 t1 
LEFT JOIN Table2 t2 ON t1.id = t2.id 
WHERE t1.user=\'bob\';

Does the WHERE clause run afte

相关标签:
7条回答
  • 2020-12-13 13:55

    The where clause will be executed before the join so that it doesn't join unnecessary records. So your code is fine the way it is.

    0 讨论(0)
  • 2020-12-13 14:00

    you can do

    SELECT * 
        FROM Table1 t1 
        LEFT JOIN Table2 t2
            ON t1.id=t2.id AND t1.user='bob';
    
    0 讨论(0)
  • 2020-12-13 14:07

    In my experience in a left join you cannot exclude records in the 'left' (t1) table in the ON-statement since - by definition - all t1 records will be included. The where statement does work as it will be applied to the result of the join afterwards.

    I do not exactly know what you want to achieve but most probably an inner join suits your needs as well and then you can add the t1.user='bob' condition to the ON-statement.

    But if Mosty Mostacho is correct, the location (WHERE vs ON) of the condition is not relevant for speed of execution.

    0 讨论(0)
  • 2020-12-13 14:09

    You should just add t1.user='bob' condition to ON clause before other condition and it will be evaluated first:

    SELECT * FROM Table1 t1 
    LEFT JOIN Table2 t2
    ON t1.user='bob' AND t1.id = t2.id;
    
    0 讨论(0)
  • 2020-12-13 14:10

    What you may use is table expression after FROM like this:

    SELECT *
    FROM (SELECT
            id
        FROM Table1
        WHERE user = 'bob') AS t1
    LEFT JOIN Table2 t2
        ON t1.id = t2.id
    
    0 讨论(0)
  • 2020-12-13 14:12

    RIGHT JOIN was the solution:

    SELECT cars.manufacturer, cars.year FROM cars 
    RIGHT JOIN (SELECT m.manufacturer FROM cars AS m ORDER BY m.year DESC LIMIT 3) subq 
    ON cars.manufacturer=subq.manufacturer
    

    Haven't put it through the full rigors yet, but seems to work.

    0 讨论(0)
提交回复
热议问题