如何将多个SQL查询合并为一个?

时间:2012-03-10 20:53:30

标签: sql

我有这些多个sql查询,我想将它们捆绑到一个单独的查询中,这样我就可以避免从我的应用程序向数据库发送多个请求(我希望一次性接收所有这些数据):< / p>

1) select pin, officeNum, isVeteran from table18 where pin = 123;

2) select streetAddress, apartmentAddress, cityAddress, stateAddress from table1 where case = (select case from table18 where pin = 123);

3) select unitAddress, cityAddress, streetAddress, apartmentAddress from table5 where pin = 123;

4) select unitAddress, cityAddress, streetAddress, apartmentAddress from table55 where seqNum = 0 and rfa = (select rfa from table18 where pin = 123);

5) select unitAddress, cityAddress, streetAddress, apartmentAddress from table103 where histCode = 0 and case = (select case from table18 where pin = 123);

6) select phone, email from table715 where histSeqNum in (select max(histSeqNum from table715))
      and histCode in (select max(histCode) from table715)
      and case = (select case from table18 where pin = 123);

这是我的架构:

(请原谅糟糕的设计,它来自20年前创建的数据库,没有外键)

-Table18(pin(PK),case,officeNum,isVeteran)

-Table1(case(PK),caseOfficer,streetAddress,apartmentAddress,cityAddress,stateAddress)

-Table5(pin(PK),streetAddress,apartmentAddress,cityAddress,stateAddress)

-Table55(rfa(CompositeKey),seqNum(CompositeKey),rfaAddress,streetAddress,apartmentAddress,cityAddress,stateAddress)

-Table103(case(CompositeKey),histCode(CompositeKey))

-Table715(case(CompositeKey),histSeqNum(CompositeKey),histCode(CompositeKey),电话,电子邮件)

2 个答案:

答案 0 :(得分:3)

你做不到。所有查询都返回固定数量的列。如果仍然坚持以这种方式检索列,请确保所有查询的columns数据类型相同,并将它们与联合组合。我不建议这样做,但这是可能的。

答案 1 :(得分:3)

这是一个可以联合的集合...... (3,4,5)

select unitAddress, cityAddress, streetAddress, apartmentAddress 
from table5 where pin = 123
union
select unitAddress, cityAddress, streetAddress, apartmentAddress 
from table55 where seqNum = 0 and rfa = (select rfa from table18 where pin = 123)
union
select unitAddress, cityAddress, streetAddress, apartmentAddress 
from table103 where histCode = 0 and case = (select case from table18 where pin = 123);
如果你不介意这些空白状态,你可以把(2)放在那里......

例如,在2中写下类似的东西:

select null unitAddress, streetAddress, apartmentAddress, cityAddress, stateAddress 
from table1 
where case = (select case from table18 where pin = 123);
union
select unitAddress, cityAddress, streetAddress, apartmentAddress, null
from table5 where pin = 123
union
select unitAddress, cityAddress, streetAddress, apartmentAddress, null 
from table55 where seqNum = 0 and rfa = (select rfa from table18 where pin = 123)
union
select unitAddress, cityAddress, streetAddress, apartmentAddress, null
from table103 where histCode = 0 and case = (select case from table18 where pin = 123);

还考虑重组你的嵌套选择加入 - 类似于:(我打赌优化这些查询将是你正在寻找的性能差异)

select streetAddress, apartmentAddress, cityAddress, stateAddress 
from table1  t1, table18 t18
where t1.case = t18.case 
and t18.123;

然后确保t18在引脚上有一个索引,而t1在case上有一个索引。