2012-04-26 36 views
1

我有一個sql查詢,我檢查一個值是否在表的最大值和最小值之間。現在我已經實現這個如下:如何以有效的方式使用min()和max()?

SELECT spectrum_id, feature_table_id 
FROM 'spectrum', 'feature' 
WHERE `spectrum`.msrun_msrun_id = 1 
AND `feature`.msrun_msrun_id = 1 
AND (SELECT min(rt) FROM `convexhull` WHERE `convexhull`.feature_feature_table_id = `feature`.feature_table_id) <= scan_start_time 
AND scan_start_time <= (SELECT max(rt) FROM `convexhull` WHERE 'convexhull'.feature_feature_table_id = 'feature'.feature_table_id) 
AND (SELECT min(mz) FROM `convexhull` WHERE `convexhull`.feature_feature_table_id = `feature`.feature_table_id) <= base_peak_mz 
AND base_peak_mz <= (SELECT max(mz) FROM `convexhull` WHERE `convexhull`.feature_feature_table_id = `feature`feature_table_id) 

這是運行速度很慢,因爲我從凸形輪廓選擇我每次運行此查詢時間爲4倍,所以我嘗試使用內,以改善其加入:

SELECT spectrum_id, feature_table_id 
FROM 'spectrum', 'feature' 
INNER JOIN `convexhull` ON `convexhull`.feature_feature_table_id = `feature`.feature_table_id 
WHERE `spectrum`.msrun_msrun_id = ? "+ 
AND `feature`.msrun_msrun_id = ? "+ 
AND min(`convexhull`.rt) <= scan_start_time "+ 
AND scan_start_time <= max(`convexhull`.rt) "+ 
AND min(`convexhull`.mz) <= base_peak_mz "+ 
AND base_peak_mz <= max(`convexhull`.mz)", spectrumFeature_InputValues) 

但是,min()和max()語句只能在select語句後使用。我怎樣才能使第一個查詢更高效,這樣我就可以得到最小和最大rt和mz而不必執行4個查詢?

回答

6

編輯:有幾個分鐘,又看了一遍,實現所有數據來自一個表,這樣的事情應該工作

SELECT 
    spectrum_id 
    ,feature_table_id 
FROM 
    spectrum AS s 
    INNER JOIN feature AS f 
     on f.msrun_msrun_id = s.msrun_msrun_id 
    INNER JOIN (select 
     feature_feature_table_id 
     ,min(rt) AS rtMin 
     ,max(rt) AS rtMax 
     ,min(mz) AS mzMin 
     ,max(mz) as mzMax 
    FROM 
     convexhull 
    GROUP BY 
     feature_feature_table_id 
    ) AS t 
    ON t.feature_feature_table_id = f.feature_table_id 
WHERE 
    s.msrun_msrun_id = 1 
    AND s.scan_start_time >= t.rtMin 
    AND s.scan_start_time <= t.rtMax 
    AND base_peak_mz >= t.mxMin 
    AND base_peak_mz <= t.mzMax 

我想你想從凸形輪廓表和組通過選擇feature_feature_table_id獲取該分組中的最小和最大rt。

然後,您可以將該選擇放在括號中給它一個名稱(如t)並加入它。

希望這是足夠多的讓你的道路上。如果不是在這裏創建示例模式:http://sqlfiddle.com/

,並在您的查詢,我可以修改它。

作爲一個方面說明,我想你婉加入就某一特定領域這些表,而不是選擇都與where子句比較:

SELECT spectrum_id, feature_table_id 
FROM 'spectrum', 'feature' 
WHERE `spectrum`.msrun_msrun_id = 1 
AND `feature`.msrun_msrun_id = 1 

和:

SELECT 
    spectrum_id 
    ,feature_table_id 
FROM 
    spectrum AS s 
    INNER JOIN feature AS f 
     on f.msrun_msrun_id = s.msrun_msrun_id 
WHERE 
    s.msrun_msrun_id = 1 

如果我在那裏有什麼問題讓我知道。

+0

我剛完成測試,你寫的最上面的部分,它使查詢快了3倍,謝謝!只要數據仍然正確,只要 – 2012-04-26 13:42:58

+0

;-) – gordatron 2012-04-26 13:51:29