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

相关推荐
大数据追光猿4 分钟前
【大数据生产问题】Flink CDC 同步 MySQL 到 StarRocks 时因字段新增导致任务失败?
大数据·数据库·mysql·flink
大布布将军7 分钟前
⚡️ 性能加速器:利用 Redis 实现接口高性能缓存
前端·数据库·经验分享·redis·程序人生·缓存·node.js
野生风长7 分钟前
从零开始的C语言:文件操作与数据管理(下)(fseek,ftell,rewind,文件的编译和链接)
android·java·c语言·开发语言·visual studio
Ahuuua9 分钟前
Spring 事务传播行为详解
数据库·sql·spring
武子康9 分钟前
Java-210 Spring AMQP 整合 RabbitMQ:JavaConfig 注解配置、RabbitTemplate 发送/同步接收与坑位速查
xml·java·spring·消息队列·rabbitmq·java-rabbitmq·mq
Change!!9 分钟前
uniapp写的h5,怎么根据页面详情,设置不同的标题
前端·uni-app·标题
浅箬10 分钟前
uniapp 打包之后出现shadow-grey.png去除
前端·uni-app
2345VOR10 分钟前
【ESP32C3接入2025年冬火山大模型教程】
开发语言·数据库·豆包·火山
IvanCodes11 分钟前
openGauss 核心体系架构深度解析
数据库·sql·postgresql·openguass
陌路2012 分钟前
redis主从复制
数据库·redis