[英]combining two sql queries into one?
我在同一張表上有兩個類似的查詢,在相同的條件下但對它的選擇不同。
Select flatpos from archdetails
where version='1.3' AND compname IN (
select distinct compname from svn3 where revno='r270294'
)
和
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'
)
如您所見,查詢位於同一表的archdetails
並且兩者的條件也相同。
查詢1將輸出類似
12
47
查詢2將輸出類似
396 43 1
我希望輸出是
12 396 43 1
47 396 43 1
我顯然不能將它們組合在一起。
這些查詢中的每個查詢都在x時間內運行。 我知道我可以將這些查詢放入新查詢的from子句中並獲得所需的結果,但是新查詢將以2倍的時間運行。
有沒有一種更快的方法,因為數據庫實際上只需要掃描一次,然后只需格式化即可。
謝謝
將第一個查詢的結果選擇到臨時表中。
然后,要獲取第一個結果集,請從該臨時表中select *
。
要獲得第二個結果集,請將臨時表連接到第二個查詢,而沒有其他where子句語句,也不會從臨時表中選擇任何列。
(如果優化器設法以某種方式設法執行了第二次查詢,則將第二次查詢的結果存儲到第二個臨時表中並聯接2個臨時表)
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
更新:
您可能可以通過'select distinct compname from svn3 where revno='r270294''
刪除'select distinct compname from svn3 where revno='r270294''
之一來獲得一些'select distinct compname from svn3 where revno='r270294''
通過
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.