Mysql 的 WITH 语法

1 WITH AS 短语

也叫做子查询部分(subquery factoring),是用来定义一个SQL片断

with t as (
select * from consumer
)
select * from t

该语句的作用是在, 大量的报表查询时, 使用 with as 可以提取出大量的子查询, 更加简洁

2 WITH 特性

  • with 其实就是一个子查询抽取出来,换了一个别名
  • 和视图的区别:with as 等同于一次性视图,只会持续到下一个查询。在之后就不能再被引用
  • 主要用于简化复杂的 数据集 和 递归

注:with 语法,不适合 mysql 8.0 版本之前

3 旧版本替代方案 temporary table

5.6 / 5.7 版本, with 的替代品

CREATE TEMPORARY TABLE detail 
  SELECT id, end_time, status
  FROM t_wl_record_repairs_detail
  WHERE end_time IS NULL;

SELECT COUNT(1) as sum, 'today' as name FROM detail...
UNION
SELECT COUNT(1) as sum, 'd1' as name....
UNION...
  • 作用:临时表用来保存一些 ‘临时数据’

  • 特点:

    1. 临时表 仅在 ‘当前连接’ 可见,当关闭连接时,Mysql 会 ‘自动删除表数据及表结构’
    2. 临时表 和 普通表 用法一样,用关键字 ‘temporary’ 予以区别
-- 可以手动 insert
insert into temporary_test(tid, tname) values(1, 'a');
insert into temporary_test(tid, tname) values(2, 'b');
-- 也可手动 delete 和 drop
drop temporary table if exists temporary_test;

公共表表达式(CTEs)

公共表表达式(CTEs)是一个命名的临时结果集。CTE不作为对象存储,仅在查询执行期间持续

Common table expressions (CTEs) in SQL Server provide us with a tool that allows us to design and organize queries in ways that may allow faster development, troubleshooting, and improve performance. In the first part of this series, we’ll look at querying against these with a practice data set. From examples of wrapped query checks to organization of data to multiple structured queries, we’ll see how many options we have with this tool and where it may be useful when we query data.

WITH cte_name AS (
    query
);

ps: WHERE 语句 AND && 优先级高于 OR ||

你可能感兴趣的:(DB,sql)