2015-06-11 30 views
-1

我有以下查询。如何重新构建SQL查询,以便我可以轻松地编写/引用它们

Select * from (
    Select a, b, c, d, from t1 
    Union 
    Select a, b, c, d from t2 
) where a is not null and order by b. 

现在我必须根据上述结果集从另一个表中提取数据。

Select * from (Select * from (
     Select a, b, c, d, from t1 
     Union 
     Select a, b, c, d from t2 
     ) 

    where a is not null and order by b) 

as tempT1 left outer join t3 on tempT1.a = t3.a 

我必须进一步使用这个结果集来形成另一个选择查询。所以,以上风格的写作会随着时间的推移而变得复杂。随着时间的推移,这个查询将会很复杂。

如何让它变得简单?我可以将部分结果转储到另一个表吗?

+1

您似乎正在混合查询语法与问题中使用的英语。你能纠正一下吗?另外,请根据具体情况标记具体的技术细节。 – DarkKnight

+0

您的查询中至少有一个语法错误。 (取决于使用的dbms ...你使用哪一个?) – jarlh

回答

0

使用temporary表。重写查询,作为

Select * into #tempResult1 from (
Select a, b, c, d, from t1 
Union 
Select a, b, c, d from t2 
) where a is not null and order by b 

现在对于下一个查询,上面temp table作为

Select * into #tempResult2 
from #tempResult1 
left outer join t3 on tempT1.a = t3.a 

现在不是写这个查询,只需使用#tempResult2使用。

select * from #tempResult2 
0

可以使用Comman表表达式或临时表或表变量

with cte as 
(
Select a, b, c, d from t1 
Union 
Select a, b, c, d from t2 
) 
, 
cte2 as 
(
select * cte where a is not null and order by b 
) 
select * from cte2 c left outer join t3 on c.a = t3.a 

使用临时表

select * into #temp1 
from 
(
Select a, b, c, d from t1 
    Union 
    Select a, b, c, d from t2 
) 

select * into #temp2 from #temp1 where a is not null and order by b 

select * from temp2 c left outer join t3 on c.a = t3.a 
+0

几个语法错误。 (一些复制和粘贴...) – jarlh

+0

请给我错误.. @ jarlh – Dhaval

+0

例如“d,from”。 (我知道它只是从问题中复制而来!) – jarlh

0

假设你正在使用SQL Server,你可以简化像下面。不是编译版本。但是你可以使用它作为伪代码。

with cte as 
(
     Select a, b, c, d from t1 where a is not null 
     Union 
     Select a, b, c, d from t2 where a is not null 
) 

select * from cte tempT1 left outer join t3 on tempT1.a = t3.a order by tempT1.b 
+0

你选择的语句是什么意思.. ??你定义了两个表分开他们.. !!你不觉得它会导致错误.. – Dhaval

+0

你在说什么?你在问哪个表?你的问题不清楚。请详细说明。 – DarkKnight

0

你也有一些错误的SQL语法。尝试:

; 
WITH Q1 
      AS (SELECT a , 
         b , 
         c , 
         d 
       FROM  t1 
       UNION 
       SELECT a , 
         b , 
         c , 
         d 
       FROM  t2 
       ), 
     Q2 
      AS (SELECT * 
       FROM  Q1 
       ) 
    SELECT * 
    FROM Q2 tempT1 
      LEFT OUTER JOIN t3 ON tempT1.a = t3.a 
    WHERE a IS NOT NULL 
    ORDER BY b 
1

您可以创建的意见,将取代这些内的SELECT
w3schools
“在SQL中,视图是基于SQL语句的结果集的虚拟表。 视图包含行和列,就像真实的表一样,视图中的字段是数据库中一个或多个实际表的字段 您可以将SQL函数,WHERE和JOIN语句添加到视图并显示数据就好像数据来自单个表格一样。“

文档他们,所以你不会迷路,就是这样......

+0

CTE只能使用一次。临时表是一种痛苦。鉴于有限的解释,观点是最好的解决方案。 –

相关问题