如何跨 UNION 重复 SQL 查询的部分? (SQL 中的 DRY)
我有一个查询返回三个 UNION 查询的结果。每个查询都有一个冗长的 select 语句。 select 语句的某些部分如下所示:
coalesce(a.fact1,'Fact1'),
coalesce(b.fact1,'Fact2')
...
from/join 部分也很大等
from table1 t1
join table2 t2 on t1.id = t2.t1_id
join table3 t3 on t2.id = t3.t2_id
。每个块在所有三个 SELECT 语句中都以相同的方式重复。
我想知道是否有一种方法可以将这段代码(字段名称块或连接语句块)放入可以在一行中引用它们的位置。有点像迷你视图/功能,但只是用作文本替换。这样,我可以编辑这些内容一次,而不必单独编辑每个 select 语句的相关位。
这是在 MSSQL 中。有什么办法可以做到我想要解释的事情吗?
更新
select a.field1, b.field2, c.field3
from table1 a
join table2 b on a.id = b.table1_id
join table3 c on b.id = c.table2_id
where cond1 = 'Pos Condition'
AND cond2 = 'Test'
union
select a.field1, b.field2, d.field3
from table1 a
join table2 b on a.id = b.table1_id
join table3 c on b.id = c.table2_id
join table4 d on c.id = d.table3_id
where cond1 = 'Pos Condition'
AND cond2 = 'Second Type of Result'
每个字段中的数据根据结果类型略有变化。我想把 from table1 ->将 table3 部分连接到一个单独的位置,以便我可以重复插入它
I have a query that returns the results of three UNION'ed queries. Each query has a lengthy select statement. There are parts of the select statement that look like this:
coalesce(a.fact1,'Fact1'),
coalesce(b.fact1,'Fact2')
...
the from/join section is huge as well
from table1 t1
join table2 t2 on t1.id = t2.t1_id
join table3 t3 on t2.id = t3.t2_id
etc. Each of these blocks is repeated identically across all three SELECT statements.
I was wondering if there was a way to put that piece of code (either a block of field names or a block of join statements) into a place where I could reference them in one line. Kind of like a mini-view/function but simply serving as a text replacement. This way, I can edit these things once and not have to edit the relevant bit of each select statement individually.
This is in MSSQL. Is there any way to do what I'm trying to explain?
Update
select a.field1, b.field2, c.field3
from table1 a
join table2 b on a.id = b.table1_id
join table3 c on b.id = c.table2_id
where cond1 = 'Pos Condition'
AND cond2 = 'Test'
union
select a.field1, b.field2, d.field3
from table1 a
join table2 b on a.id = b.table1_id
join table3 c on b.id = c.table2_id
join table4 d on c.id = d.table3_id
where cond1 = 'Pos Condition'
AND cond2 = 'Second Type of Result'
The data in each field changes slightly based on type of result. I'd like to put the from table1 -> join table3 section in a separate place so I can insert it repeatedly
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您在问题中给出的示例可以重构为 CTE 罚款。
The example you have given in your question can be refactored into a CTE fine.
查看通用表表达式
Look into Common Table Expressions
您是否查看过公用表表达式 (CTE)?
Have you looked at Common Table Expressions (CTEs)?