我想知道是否有可能在相同的查詢中加入相同的子選擇而不必再次執行查詢?下面的查詢是實際模糊查詢我想運行SQL:是否可以加入相同的子選擇?
select * from
(
-- Sub query A - same as sub query B
select bc.service_type, bc.cid, min(bc.last_modified_date) as last_modified1 from
(
select * from table_a bc2
where bc2.state != 7
AND bc2.cid in
(
select cid from table_a TA, table_b TB
where TB.name not like '% IS' and TA.state != 7
AND TA.service_type = 1
AND TA.username is not null
and TA.bctid = TB.bctid
)
) bc
group by service_type, cid
) result1,
(
// Sub query B - same as sub query A
select bc.service_type, bc.cid, min(bc.last_modified_date) as last_modified2 from
(
select * from table_a bc2
where bc2.state != 7
AND bc2.cid in
(
-- select affected records
select cid from table_a TA, table_b TB
where TB.name not like '% IS' and TA.state != 7
AND TA.service_type = 1
AND TA.username is not null
and TA.bctid = TB.bctid
)
) bc
group by service_type, cid
) result2
where result1.service_type = 1
and result2.service_type = 2
and result1.cid = result2.cid
and result1.last_modified1 < result2.last_modified2
的重複子查詢的解釋計劃昂貴給出表的大小,所以我非常不希望兩次運行它。我正在尋找的是克隆第一個查詢的結果並將其加入自身的一些方法!
這是要在Oracle中運行的情況下,有一些數據庫特定的擴展名。
完美的感謝,我不知道那一個! – Ellis 2011-06-01 14:21:13
@Ellis:這些稱爲Common Table Expressions或簡稱CTE。 – 2011-06-01 19:35:01