简体   繁体   English

连接中过滤器的 SQL 性能与结果中的

[英]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:我需要加入 2 个表,但其中一个有一个必须应用的常量过滤器,我的问题是在性能方面哪个选项更好:

  1. Having the constant filter on the "FROM" and setting an alias like this:在“FROM”上使用常量过滤器并设置如下别名:

     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:在主查询的WHERE中设置过滤器:

     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. MySQL就是其中之一。 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.它的编写和读取都更简单,而且它的性能永远不会比子查询方法差。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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