简体   繁体   中英

SQL performance of filter in join vs in results where

I need to join 2 tables but one of them has a constant filter that has to be applied, my question is what option is better in terms of performance:

  1. Having the constant filter on the "FROM" and setting an alias like this:

     SELECT <result fields> FROM (SELECT <table A fields> FROM filtered_table WHERE field = value) AS A LEFT OUTER JOIN tableB ON A.id = tableB.id
  2. Setting the filter in the WHERE of the main query:

     SELECT <result fields> FROM filtered_table AS A LEFT OUTER JOIN tableB ON A.id = tableB.id WHERE a.field = value

Most databases will treat the two forms the same -- they are logically the same and the optimizer knows this.

Some databases tend to materialize subqueries. MySQL is one of these. In that database, the subquery would probably be more expensive, because it writes out the subquery.

I would recommend writing the code without a subquery. It is both simpler to write and read and it should never have worse performance than the subquery method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM