Difference between where and and clause in join sql query [duplicate]

青春壹個敷衍的年華 提交于 2019-12-24 17:27:54

问题


What is the difference between following two SQL queries

select a.id, a.name, a.country 
from table a 
left join table b on a.id = b.id
where a.name is not null

and

select a.id, a.name, a.country 
from table a 
left join table b on a.id = b.id and a.name is not null

回答1:


Base on the following two test result

select a.id, a.name,a.country from table a left join table b
on a.id = b.id
where a.name is not null 

is faster (237 Vs 460). As far as I know, it is a standard.




回答2:


There is no difference other than the syntax.




回答3:


  1. Performs the join, then the filter
  2. Performs the filter before the join (better performance)

EDIT: Above was my original answer, below supports it.

4 Tables, 4 left joins, about 500,000 results and the second query runs in half the time. You should choose a larger working set when trying to test out query efficiency ... or factor in CPU load, RAM usage, connection time a few other things. If you are going to have less than 1,000 records or limited traffic optimization will be hard to see or justify. It's simple to test over your working set on a production environment and use what performs better (not just in theory).

http://www.beaudurrant.com/images/sof/22302649.jpg

You can see the differences in both efficiency and results over my datasets. This example is using a mySQL database.

  1. 452,734 records in 420.016 seconds
  2. 452,747 records in 214.334 seconds

Note: Queries were made to run slow on purpose.



来源:https://stackoverflow.com/questions/22302649/difference-between-where-and-and-clause-in-join-sql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!