2012-06-27 86 views
0

我想執行一個mysql語句,我有一個選擇不是where條件的一部分。 這是我的代碼:MYSQL有多個選擇相應的條件不同的地方

SELECT oil.empid 
    , oil.mileage 
    , oil.`date` 
    , max(oil.mileage) AS expr1 

FROM 
    oil 
WHERE 
    oil.mileage < (SELECT max(oil.mileage) AS expr1 
       FROM 
        oil) 

GROUP BY 
    oil.empid 
ORDER BY 
    oil.mileage 

現在這個選擇的第二大里程,但我想要的是第二和最大行駛里程。我相信我只需要選擇WHERE以外的最大(里程),但我不知道該怎麼做。感謝您的幫助

編輯: 如果這些1497輸入的數據是

里程:100,100000,和200000

和EMPID 2000

里程:100,1500,5000

我想這樣的:

empid|2nd max | max 
1497 | 100000 | 200000 
2000 | 1500 | 5000 
+0

如何完全省略WHERE子句和限制查詢到2個結果? –

回答

1

您可以使用LIMITOFFSET在MySQL的ORDER BY子句中查找第二里程。通過這種方式,您可以不使用昂貴的GROUP BY

(更新)由OP的澄清後:

SELECT oil.empid 
    , oil.mileage 
    , oil.date 
FROM 
     oil 
    JOIN 
     (SELECT DISTINCT empid 
      FROM oil 
     ) AS emp 
      ON oil.empid = emp.empid 
      AND oil.mileage >= 
       (SELECT mileage 
        FROM oil AS o 
        WHERE o.empid = emp.empid 
        ORDER BY mileage DESC 
        LIMIT 1 OFFSET 1 
       ) 
ORDER BY 
    oil.empid 
    , oil.mileage    --- ASC or DESC here, your choice 
; 
+0

這與brians代碼的作用相同,只返回2個empid的行(在本例中爲empid =員工id),如果不清楚,我有多個empid對不起 – BluGeni

+1

向我們展示一些示例數據,並希望將其作爲結果然後。 –

+1

你想要**每** ** empid 2大里程嗎?這是一個不同的查詢... –

1

這可能是一個天真的反應,但爲什麼不只是這樣做:

SELECT oil.empid 
     , oil.mileage 
     , oil.`date` 
     , max(oil.mileage) as expr1 
FROM oil 
GROUP BY oil.empid, oil.`date` 
ORDER BY oil.mileage DESC 
LIMIT 2 

UPDATE
鑑於OP的更新很顯然,我們需要的那種完全不同的查詢,像這樣:

SELECT outer.empid 
     , (SELECT first.mileage 
      FROM oil as first 
      WHERE first.empid = outer.empid 
      ORDER BY first.mileage DESC 
      LIMIT 1) AS max 
     , (SELECT second.mileage 
      FROM oil as second 
      WHERE second.empid = outer.empid 
      ORDER BY second.mileage DESC 
      LIMIT 1 
      OFFSET 1) as 2nd_max 
FROM oil as outer 
+0

這將工作,如果我只想要2行返回總數我有多個empid的,它只返回一個這種方式。 – BluGeni

+0

@BluGeni你可以用你試圖用你的查詢得到的**結果**樣本來更新你的問題嗎? –

+0

添加了我的示例 – BluGeni