2012-11-09 48 views
1

我正在嘗試執行時間查詢以返回該時間點最後記錄的數量。如果條件大於返回值,請選擇上一條記錄

基本上我有一個表格式爲這樣

id | other_id | quantity | created 
1  1   5  20 
2  1   2  22 
3  1   1  25 
4  1   8  90 

如果創建查詢是60我要回的數量爲創建的25和更高 還是從最近的已知量,因爲查詢的創建。

SELECT * FROM table 
WHERE created >= 60 
AND other_id = 1 
ORDER BY ID ASC 

它返回ID:4,但我想在60這是ID創建:3 但是,如果查詢的創建是25我想回到25和更大的

大腦是個大氣壓,無法炒拿出一個正確的解決方案

+1

呵呵?我沒有看到任何60.也許開始澄清你想要什麼。 – Randy

+0

當沒有任何東西時,你如何獲得一個在60'創建的行? –

+0

創建查詢> = 60如果檢索到的記錄較新並且存在較舊的記錄,我希望以前的記錄 – fyrye

回答

1

此查詢選擇你想要的值前值:

SELECT MAX(created) 
FROM yourtable 
WHERE other_id = 1 
AND created <= 60 

然後,您可以使用此爲內部子查詢您的主要查詢:

SELECT * 
FROM yourtable 
WHERE created >= 
(
    SELECT IFNULL(MAX(created), -1) 
    FROM yourtable 
    WHERE other_id = 1 
    AND created <= 60 
) 
AND other_id = 1 
ORDER BY ID ASC 
+0

如果沒有以前的記錄IFNULL((SELECT MAX(t2.created)FROM表格t2 t2。 other_id = t1.other_id AND t2.created <=?),?)謝謝 – fyrye

1
SELECT * FROM table 
WHERE id >= (
    SELECT id FROM table WHERE created <= 60 
    AND other_id = 1 
    ORDER BY id DESC LIMIT 1 
) 
AND other_id = 1 
ORDER BY id ASC