共用表表达式(CTE)——阅读《MySQL8 Cookbook》笔记

公用表表达式(CTE)

MySQL8支持公用表达式,包括非递归和递归两种

非递归CTE

派生表:

SELECT…FROM (subquery) AS DERIVED, t1…

CTE

SELECT…WITH derived AS (subquery) SELECT … FROM derived, t1 …

CTE 可能在SELECT/UPDATE/DELETE之前,包括WITH derived AS (subquery)的子查询。

例如:了解每年工资较前一年的增长百分比
  1. 使用两次子查询实现

    SELECT 
    	q1.year,
    	q2.year AS next_year,
    	q1.sum,
    	q2.sum AS next_sum,
    	100*(q2.sum-q1.sum)/q1.sum AS pct
    FROM
    	(SELECT year(from_date) as year, sum(salary) as sum FROM salaries GROUP BY year) AS q1,
    	(SELECT year(from_date) as year, sum(salary) as sum FROM salaries GROUP BY year) AS q2
    WHERE q1.year = q2.year-1;
    

    结果:

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Rc3XHUR8-1598090911645)(公用表表达式.assets/image-20200822172257355.png)]

  2. 使用CTE实现

    WITH CTE AS
    	(SELECT year(from_date) AS year, SUM(salary) AS sum FROM salaries GROUP BY year)
    SELECT
    	q1.year, q2.year as next_year, q1.sum, q2.sum as next_sum, 100 * (q2.sum-q1.sum)/q1.sum as pct FROM
    	CTE AS q1,
    	CTE AS q2
    WHERE
    	q1.year = q2.year-1;
    

    结果:

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TKUpEdCx-1598090911653)(公用表表达式.assets/image-20200822172624373.png)]

    可以看到,使用CTE后,结果与之前相同,但查询时间缩短了50%,可读性变好,而且可以被多次引用。

递归CTE

递归CTE是一种特殊的CTE,其子查询会引用自己的名字。WITH子句必须以WITH RECURSIVE开头,递归CTE子查询包括两部分:seed查询和recursive查询,由UNION[ALL]或UNION DISTINCT分隔。

  1. seed查询

    SELECT被执行一次以创建初始数据子集

  2. recursive查询

    SELECT被重复执行以返回数据的子集,直到获取完整的结果集

当迭代不会产生任何新行时,递归会停止

格式

WITH RECURSIVE cte AS

(SELECT … FROM table_name /* seed 查询 */

UNION ALL

SELECT … FROM cte, table_name) /* recursive 查询 */

SELECT … FROM cte;

例子
  1. 打印1到5的所有数字

    WITH RECURSIVE cte(n) AS
    (SELECT 1 /*seed 查询*/
    UNION ALL
    SELECT n + 1 FROM cte WHERE n < 5 /*recursive 查询*/
    )
    SELECT * FROM cte;
    
  2. 分层次数据遍历,为每个员工生成一个组织结构图

    WITH RECURSIVE employee_paths (id, name, path) AS
    (
    	SELECT id, name, CAST(id AS CHAR(200))
        FROM employees_mgr
        WHERE manager_id IS NULL
        UNION ALL
        SELECT e.id, e.name, CONCAT(ep.path, ',', e.id)
        FROM employee_paths AS ep JOIN employees_mgr AS e
        ON ep.id = e.manager_id
    )
    SELECT * FROM employee_paths ORDER BY path;
    
    -- 其中3-4行为seed查询,7-9行为recursive查询
    
Practice makes a man perfect. But to practice, you need some knowledge and training. This book helps you with that. Most day-to-day and practical scenarios are covered in this book. Chapter 1, MySQL 8 - Installing and Upgrading, describes how to install MySQL 8 on different flavors of Linux, upgrade to MySQL 8 from previous stable releases, and also downgrade from MySQL 8. Chapter 2, Using MySQL, takes you through the basic uses of MySQL, such as creating databases and tables; inserting, updating, deleting, and selecting data in various ways; saving to different destinations; sorting and grouping results; joining tables; managing users; other database elements such as triggers, stored procedures, functions, and events; and getting metadata information. Chapter 3, Using MySQL (Advanced), covers the latest additions to MySQL 8, such as the JSON datatype, common table expressions, and window functions. Chapter 4, Configuring MySQL, shows you how to configure MySQL and basic configuration parameters. Chapter 5, Transactions, explains the four isolation levels of RDBMS and how to use MySQL for transactions. Chapter 6, Binary Logging, demonstrates how to enable binary logging, various formats of binary logs, and how to retrieve data from binary logs. Chapter 7, Backups, covers various types of backups, the pros and cons of each method, and which one to choose based on your requirements. Chapter 8, Restoring Data, covers how to recover data from varies backups. Chapter 9, Replication, explains how to set up various replication topologies. The recipes on switching a slave from master-slave to chain replication and switching a slave from chain replication to master-slave is something that will interest the readers. Chapter 10, Table Maintenance, covers cloning tables. Managing big tables is something that this chapter will make you a maestro of. Installation and usage of third-party tools is also covered in this chapter. Chapter 11, Managing Tablespace, deals with recipes that will teach the readers how to resize, create, copy, and manage tablespaces. Chapter 12, Managing Logs, takes readers through error, general query, slow query, and binary logs. Chapter 13, Performance Tuning, explains query and schema tuning in detail. There are ample recipes in the chapter that will cover this. Chapter 14, Security, focuses on the aspects of security. Recipes on securing installation, restricting networks and users, setting and resetting of passwords, and much more in covered are detail.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值