开发者

combining two sql queries into one?

开发者 https://www.devze.com 2023-01-21 06:28 出处:网络
I have two similar queries on same table and same where condition but different selects on it. Select flatpos from archdetails

I have two similar queries on same table and same where condition but different selects on it.

Select flatpos from archdetails
where version='1.3' AND compname IN (
    select distinct compname from svn3 where revno='r270294'
)

AND

select count(distinct compname),
    sum(CASE WHEN inFlat=1 THEN 1 ELSE 0 END),
    min(flatLoopIndex)
from archdetails
where version='1.3'
AND compname IN (
    select distinct compname from svn3 where revno='r270294'
)

As you can see the query is on the same table archdetails and where condition is same for both as well.

query 1 will output something like

12

47

query 2 will output something like

396 43 1

I would like the output to be

12 396 43 1

47 396 43 1

I cannot obviously combine them by a group by.

Each one of these query runs in x amount of time. I know I can just put these queries into the from clause of a new query and get t开发者_JAVA技巧he desired result but then the new query runs in 2x amount of time.

Is there a faster way around since database essentially has to be scanned just once and then it is just a matter of formatting.

Thanks


Select the results of the first query into a temp table.

Then to get the first result set, select * from that temp table.

To get the second result set, join the temp table to the second query with no additional where clause statements and no columns selected from temp table.

(If the optimizer somehow manages to execute the second query N times, stash the results of second query into second temp table and join 2 temp tables)

create temporary table tmp1
Select flatpos from archdetails
where version='1.3' AND compname IN (
    select distinct compname from svn3 where revno='r270294'
)

create temporary table tmp2
select count(distinct compname) as c,
    sum(CASE WHEN inFlat=1 THEN 1 ELSE 0 END) as s,
    min(flatLoopIndex) as m
from archdetails
where version='1.3'
AND compname IN (
    select distinct compname from svn3 where revno='r270294'
)

select * from tmp1

select tmp2.c, tmp2.s, tmp2.m from tmp1, tmp2


UPDATE:

You might be able to gain some by removing one of the 'select distinct compname from svn3 where revno='r270294''

by

SELECT ad.flatpos , 
   totals.compname, 
   totals.inFlat, 
   totals.flatlooopindex

FROM
    archdetails ad
    INNER JOIN 
    (select count(distinct compname) compname,
        sum(CASE WHEN inFlat=1 THEN 1 ELSE 0 END) inFlat,
        min(flatLoopIndex) flatlooopindex
    from archdetails
    where version='1.3'
     AND compname IN (
          select distinct compname from svn3 where revno='r270294'
    )) totals 
    ON ad.compname = totals.compname
0

精彩评论

暂无评论...
验证码 换一张
取 消