Sql query order of execution, on、where的区别

Query order of execution

  1. FROM and JOINs
    The FROM clause, and subsequent JOINs are first executed to determine the total working set of data that is being queried. This includes subqueries in this clause, and can cause temporary tables to be created under the hood containing all the columns and rows of the tables being joined.

  2. WHERE
    Once we have the total working set of data, the first-pass WHERE constraints are applied to the individual rows, and rows that do not satisfy the constraint are discarded. Each of the constraints can only access columns directly from the tables requested in the FROM clause. Aliases in the SELECT part of the query are not accessible in most databases since they may include expressions dependent on parts of the query that have not yet executed.

  3. GROUP BY
    The remaining rows after the WHERE constraints are applied are then grouped based on common values in the column specified in the GROUP BY clause. As a result of the grouping, there will only be as many rows as there are unique values in that column. Implicitly, this means that you should only need to use this when you have aggregate functions in your query.

  4. HAVING
    If the query has a GROUP BY clause, then the constraints in the HAVING clause are then applied to the grouped rows, discard the grouped rows that don’t satisfy the constraint. Like the WHERE clause, aliases are also not accessible from this step in most databases.

  5. SELECT
    Any expressions in the SELECT part of the query are finally computed.

  6. DISTINCT
    Of the remaining rows, rows with duplicate values in the column marked as DISTINCT will be discarded.

  7. ORDER BY
    If an order is specified by the ORDER BY clause, the rows are then sorted by the specified data in either ascending or descending order. Since all the expressions in the SELECT part of the query have been computed, you can reference aliases in this clause.

  8. LIMIT / OFFSET
    Finally, the rows that fall outside the range specified by the LIMIT and OFFSET are discarded, leaving the final set of rows to be returned from the query.
    sql-order.png

on、where的区别

  1. ON后面的筛选条件主要是针对关联表的(对于主表的筛选条件不适用)
  2. 对于主表的筛选条件应该放在where后面,不应该放在ON后面
  3. 如果查询条件查询后才join连接应该把查询条件放在ON后面;如果要连接完毕后才筛选应该4. 把条件放在where后面
  4. 对于关联表可以先做子查询再join

参考文章

Order of execution of a Query
mysql中join后on、where的区别
SQL Joins Using WHERE or ON

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值