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

时间:2015-06-11 04:39:25

标签: 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

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

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

5 个答案:

答案 0 :(得分:1)

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

记录它们,这样你就不会迷路而且就是这样......

答案 1 :(得分:0)

您可以使用 Comman Table表达式或Temp Table或Table Variable

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

答案 2 :(得分:0)

假设您使用的是SQL Server,您可以简化以下内容。不是编译版本。但你可以将它用作伪代码。

<?php

    $data = json_decode(file_get_contents("php://input"));

    $firstname = mysql_real_escape_string($data->firstname);
    $lastname = mysql_real_escape_string($data->lastname);
    $username = mysql_real_escape_string($data->username);
    $address1 = mysql_real_escape_string($data->address1);
    $address2 = mysql_real_escape_string($data->address2);
    $city = mysql_real_escape_string($data->city);
    $state = mysql_real_escape_string($data->state);
    $zip = mysql_real_escape_string($data->zip);
    $password = mysql_real_escape_string($data->password);

    mysql_connect("localhost","root","");
    mysql_select_db("mydatabase");
    mysql_query("INSERT INTO users (`firstname`, `lastname`, `username`, `password`, `address1`, `address2`, `city`, `state`, `zip`)VALUES('" . $firstname . "','" . $lastname . "','" . $username . "','" . $password . "','" . $address1 . "','" . $address2 . "','" . $city . "','" . $state . "','" . $zip . "')");

?>

答案 3 :(得分:0)

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

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

答案 4 :(得分: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