2012-08-29 143 views
0

您好我需要做下面的使用標準休眠:加入標準

Select * from product pd, (Select productID pd1 from ... where ...) tpd1, 
(Select productID pd2 from ... where ...) tpd2 
where pd.productID = tpd1.pd1 and pd.productID = tpd1.pd2 

我想知道是否有可能?

原來的SQL使用IN條件

Select * from product pd where productID in (Select productID pd1 from ... where ...) and 
productID in (Select productID pd2 from ... where ...) 

,但得到的結果時間過久,使用連接的SQL語句,我能夠得到我的結果更快。

有幫助嗎?

+0

請張貼原始查詢的解釋計劃。 –

回答

0

鑑於您在使用Hibernate,你可能不得不做這樣的事情,這應該工作正常,如果預期的匹配數量相對較低:

select * 
from product pd 
where pd.productID in 
    (select productID 
    from product pd2 
    join tpd1 on (pd2.productID = tpd1.pd1) 
    join tpd2 on (pd2.productID = tpd2.pd2) 
    where tpd1.... 
    and tpd2.... 
    ); 

我假設有一個唯一索引product.productID

或者,你可以嘗試EXISTS配方,它可能會或可能不會比你原來的查詢工作得更好:

select * 
from product pd 
where EXISTS 
    (select null from tpd1 where pd.productID = tpd1.pd1 and ...) 
and EXISTS 
    (select null from tpd2 where pd.productID = tpd2.pd2 and ...) 
; 
+0

我目前使用hibernate標準來推薦你的解決方案,但是由於select語句的某些內容已經非常滯後。我嘗試使用SQL優化器,並推薦使用連接表。您建議的解決方案的OUTLINER輸入不會加載,但對於連接表查詢,它將加載。其中一個原因是因爲返回的數據量很大。 – seesee

+0

對於所有建議的查詢,您確實需要爲您的查詢發佈解釋計劃 - 甚至更好。沒有這個計劃,我們所能做的只是猜測。 –