复杂查询:直接查询/子查询/视图/CTE

原始查询示例:

sql 复制代码
select
	a,
	b,
	c,
	d1,
	d2,
	case
		when d1 is not null
		and d1 <> ''
		and d2 is not null
		and d2 <> ''
                       then CONCAT(d1, '*', d2)
		when d1 is not null
		and d1 <> '' then d1
		when d2 is not null
		and d2 <> '' then d2
		else ''
	end as d_desc
from
	t_test

直接查询:

sql 复制代码
select
	a,
	b,
	c,
	d1,
	d2,
	case
		when d1 is not null
		and d1 <> ''
		and d2 is not null
		and d2 <> ''
                       then CONCAT(d1, '*', d2)
		when d1 is not null
		and d1 <> '' then d1
		when d2 is not null
		and d2 <> '' then d2
		else ''
	end as d_desc
from
	t_test
where
	(case
		when d1 is not null
		and d1 <> ''
		and d2 is not null
		and d2 <> ''
                       then CONCAT(d1, '*', d2)
		when d1 is not null
		and d1 <> '' then d1
		when d2 is not null
		and d2 <> '' then d2
		else ''
	) = 'aaa'

子查询:

sql 复制代码
select
	*
from
	(
	select
		a,
		b,
		c,
		d1,
		d2,
		case
			when d1 is not null
			and d1 <> ''
			and d2 is not null
			and d2 <> ''
                       then CONCAT(d1, '*', d2)
			when d1 is not null
			and d1 <> '' then d1
			when d2 is not null
			and d2 <> '' then d2
			else ''
		end as d_desc
	from
		t_test
 ) as t_test_all
where
	d_desc = 'aaa'

视图:

sql 复制代码
CREATE VIEW t_test_view AS
(
	select
		a,
		b,
		c,
		d1,
		d2,
		case
			when d1 is not null
			and d1 <> ''
			and d2 is not null
			and d2 <> ''
                       then CONCAT(d1, '*', d2)
			when d1 is not null
			and d1 <> '' then d1
			when d2 is not null
			and d2 <> '' then d2
			else ''
		end as d_desc
	from
		t_test
)
select * from t_test_view where d_desc = 'aaa'

CTE (Common Table Expressions) :

sql 复制代码
WITH t_test_all AS (
(
	select
		a,
		b,
		c,
		d1,
		d2,
		case
			when d1 is not null
			and d1 <> ''
			and d2 is not null
			and d2 <> ''
                       then CONCAT(d1, '*', d2)
			when d1 is not null
			and d1 <> '' then d1
			when d2 is not null
			and d2 <> '' then d2
			else ''
		end as d_desc
	from
		t_test
)

**CTE(Common Table Expressions)**是SQL中的一种临时结果集,可以在SELECT、INSERT、UPDATE或DELETE语句中引用。

适用场景

简化复杂查询 : 将多层嵌套的子查询转换为清晰的CTE结构

避免重复计算 : 当同一子查询需要多次使用时

递归查询 : 处理树形结构数据(如组织架构、分类目录)

数据分析: 分步进行数据处理和分析

版本兼容性

MySQL: 8.0+ 版本支持

PostgreSQL: 较早版本就已支持

SQL Server: 2005+ 版本支持

Oracle: 较早版本就已支持

相关推荐
隔壁小邓1 分钟前
vue如何拆分业务逻辑
前端·javascript·vue.js
minji...3 分钟前
Linux 进程间通信(一)进程间通信与匿名管道
linux·运维·服务器·数据结构·数据库·c++
En^_^Joy5 分钟前
Ajax与Axios:现代前端异步请求指南
前端·javascript·ajax
XDHCOM7 分钟前
ORA-12532: TNS:invalid argument 故障解析,Oracle报错远程处理技巧与修复方法分享
数据库·oracle
码农的小菜园8 分钟前
Java线程池学习笔记
java·笔记·学习
Cobyte9 分钟前
来,实现一个 Mini Claude Code:从底层理解 AI Agent
前端·aigc·ai编程
SuperEugene9 分钟前
Vue3 + Element Plus 表单校验实战:规则复用、自定义校验、提示语统一,告别混乱避坑|表单与表格规范篇
开发语言·前端·javascript·vue.js·前端框架
IMPYLH12 分钟前
Linux 的 csplit 命令
linux·运维·服务器·数据库
酉鬼女又兒12 分钟前
零基础快速入门前端JavaScript 浏览器环境输入输出语句全解析:从弹框交互到控制台调试(可用于备赛蓝桥杯Web应用开发赛道)
前端·javascript·职场和发展·蓝桥杯·js
清汤饺子13 分钟前
搞懂 Cursor 后,我一行代码都不敲了《实战篇》
前端·javascript·后端