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

相关推荐
不坑老师20 小时前
不坑盒子的插入网页功能是完全免费的!
前端·html
毕设源码-朱学姐20 小时前
【开题答辩全过程】以 基于Java的医务室病历管理小程序为例,包含答辩的问题和答案
java·开发语言·小程序
Wang's Blog20 小时前
前端FAQ: 描述⼀下你最近使⽤过的前端框架,并解释为何选择它们?
前端·vue.js·faq
wgego20 小时前
做题笔记BUU (XSS-Lab)(1-14)
前端·笔记·xss
沐浴露z20 小时前
详解 零拷贝(Zero Copy):mmap、sendfile、DMA gather、splice
java·网络·操作系统
kyle~20 小时前
C++---关键字constexpr
java·开发语言·c++
dllxhcjla20 小时前
css第二天
java·前端·css
春生野草20 小时前
SpringBoot配置文件
java·数据库·spring boot
远航_20 小时前
10 个被严重低估的 JS 特性,直接少写 500 行代码
前端·javascript
起这个名字20 小时前
感觉这篇 DeepSeek 给出的微前端实践很牛!轻喷!
前端