简体   繁体   English

哪个是带过滤器的更快子查询,然后加入或加入查询,然后在 MYSQL 中过滤

[英]Which is faster subquery with filter and then join or join the queries and then filter in MYSQL

I have two table one is user table other is specialty table.我有两张表,一张是用户表,另一张是专业表。 Fields in user table: userid, username, userLocation Fields in specialty table: userid, userSpecialty用户表中的字段:userid、username、userLocation 专业表中的字段:userid、userSpecialty

Now I want to join there two tables.现在我想加入两个表。 Please let me know which approach will be better:请让我知道哪种方法会更好:

select * from ( select * from user where userLocation = 'value') u inner join specialty s on u.userid = s.userid; or或者

select * from user u inner join specialty s on u.userid = s.userid where userLocation = 'value';

Is it good practice to minimize the number of records where ever we can or SQL optimizer will do that automatically?尽量减少记录数量或 SQL 优化器会自动做到这一点是一种很好的做法吗?

For best shot at optimal performance, give preference to the pattern in the second query, the query without the inline view.为了获得最佳性能,请优先考虑第二个查询中的模式,即没有内联视图的查询。

For earlier version of MySQL (version 5.5 and earlier), the first query will require MySQL to run the inline view query, and materialize a derived table ( u ).对于较早版本的 MySQL(5.5 及更早版本),第一个查询将要求 MySQL 运行内联视图查询,并具体化派生表 ( u )。 Once that is done, the outer query will run against the derived table.完成后,外部查询将针对派生表运行。 And that table won't be indexed.并且该表不会被索引。 For large sets, that can be a significant performance hit.对于大型集,这可能会严重影响性能。 For small sets, the performance impact for a single query isn't noticeable.对于小型集合,单个查询的性能影响并不明显。

With the second query, the optimizer isn't forced to create and populate a derived table, so there's potential for better performance.对于第二个查询,优化器不会被迫创建和填充派生表,因此有可能获得更好的性能。

The existence of suitable indexes (or the non-existence of indexes) i0ndexes is going to have a much bigger impact on performance.存在合适的索引(或不存在索引)i0ndex 将对性能产生更大的影响。 And retrieving all columns including columns that aren't needed by the query (SELECT *) also has an impact on performance.检索所有列,包括查询不需要的列 (SELECT *) 也会对性能产生影响。 Specifying a subset of the columns, the expressions that are actually needed, will give better performance, especially if a covering index is available to avoid lookups to the underlying data pages of the table.指定列的一个子集,即实际需要的表达式,将提供更好的性能,尤其是当覆盖索引可用以避免查找表的基础数据页时。

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

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