原始查询示例:
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: 较早版本就已支持