复杂查询:直接查询/子查询/视图/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: 较早版本就已支持

相关推荐
胖咕噜的稞达鸭5 小时前
算法入门:滑动窗口--->找到字符串中所有的字母异位词,串联所有的子串,最小覆盖子串
数据库·redis·算法
zengyuhan5035 小时前
Windows BLE 开发指南(Rust windows-rs)
前端·rust
Bro_cat5 小时前
Java基础
java·开发语言·面试
醉方休5 小时前
Webpack loader 的执行机制
前端·webpack·rust
SelectDB5 小时前
上海证券 SelectDB 升级实践:湖仓流批一体落地与 Elasticsearch 全面替换
数据库·apache
一个天蝎座 白勺 程序猿5 小时前
KingbaseES在政务领域的应用实践——武汉人社大数据平台“数字化服务新模式”
大数据·数据库·政务·kingbasees·金仓数据库
前端老宋Running5 小时前
一次从“卡顿地狱”到“丝般顺滑”的 React 搜索优化实战
前端·react.js·掘金日报
隔壁的大叔5 小时前
如何自己构建一个Markdown增量渲染器
前端·javascript
用户4445543654265 小时前
Android的自定义View
前端
一起养小猫5 小时前
《Java数据结构与算法》第三篇(下)队列全解析:从基础概念到高级应用
java·开发语言·数据结构