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

相关推荐
Go高并发架构_王工3 小时前
MySQL内存优化:缓冲池与查询缓存调优技术详解
数据库·mysql·缓存
goTsHgo3 小时前
Spring XML 配置简介
xml·java·spring
正义的大古3 小时前
OpenLayers地图交互 -- 章节九:拖拽框交互详解
前端·vue.js·openlayers
青柠编程3 小时前
基于 Spring Boot 的医疗病历信息交互平台架构设计
java·spring boot·后端
专注代码七年3 小时前
IDEA JVM优化配置idea64.vmoptions - 保守兼容版本 兼容IDEA 2023.3.6版本【亲测可用】
java·jvm·intellij-idea
三十_A3 小时前
【实录】使用 Verdaccio 从零搭建私有 npm 仓库(含完整步骤及避坑指南)
前端·npm·node.js
疯癫的老码农3 小时前
【word解析】Java文件解析问题排查:无法找到OMML2MML.xsl的IO异常解析
java·开发语言·spring boot·spring·maven
huangql5203 小时前
从零到一打造前端内存监控 SDK,并发布到 npm ——基于 TypeScript + Vite + ECharts的解决方案
前端·typescript·echarts
weixin_456904273 小时前
离线下载npm包
前端·npm·node.js