CTE(Common Table Expressions)的用法二例

简介: CTE是SQL标准定义的语法,很多主流的数据库都支持,但不包括MySQL。 CTE的作用应该主要有两个,下面用PostgreSQL的例子进行演示。 1. 简化查询的写法,相同的语义用子查询会由于嵌套太深而不易理解。
CTE是SQL标准定义的语法,很多主流的数据库都支持,但不包括MySQL。 

CTE的作用应该主要有两个,下面用PostgreSQL的例子进行演示。
1. 简化查询的写法,相同的语义用子查询会由于嵌套太深而不易理解。                                                                                        
例:删除数据表中的重复记录

点击(此处)折叠或打开      

  1. with tbx(ctid,rank) as (
  2.     select ctid, rank() over (partition by tb.* order by ctid) rank from tb
  3. )
  4. delete from tb where ctid in(select ctid from tbx where rank > 1);

2. 通过递归玩出一些有用又好玩的花样
例:计算1到100的和                    

点击(此处)折叠或打开

  1. WITH RECURSIVE t(n) AS (
  2.     VALUES (1)
  3.   UNION ALL
  4.     SELECT n+1 FROM t WHERE n 100
  5. )
  6. SELECT sum(n) FROM t;


相关文章
|
5月前
|
数据库
解决which is not functionally dependent on columns in GROUP BY clause;...sql_mode=only_full_group_by
解决which is not functionally dependent on columns in GROUP BY clause;...sql_mode=only_full_group_by
42 0
|
7月前
|
存储 SQL 关系型数据库
1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column的解决办法
1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column的解决办法
87 0
|
9月前
|
SQL 关系型数据库 数据库
PG/GP group by expression语法
PG/GP group by expression语法
82 1
|
SQL 关系型数据库 MySQL
报错:[Err] 1055 - Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregat
报错:[Err] 1055 - Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregat
280 0
报错:[Err] 1055 - Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregat
|
SQL 关系型数据库 MySQL
MySQL - Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column
MySQL - Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column
157 0
|
SQL 关系型数据库 MySQL
Mysql报错: ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregate
Mysql报错: ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregate
183 0
|
SQL 关系型数据库 MySQL
Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggre
Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggre
344 0
One order search dynamic sql statement生成位置
One order search dynamic sql statement生成位置
One order search dynamic sql statement生成位置
|
SQL 数据库
Database specific hint in One order search
Database specific hint in One order search
109 0
Database specific hint in One order search