0

我想执行一个 mysql 语句,其中我有一个不属于 where 条件的选择。这是我的代码:

    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 之外选择 max(mileage),但我不知道该怎么做。谢谢你的帮助

编辑:如果为这些 1497 输入的数据是

里程数:100、100000 和 200000

对于 empid 2000

里程:100 , 1500 , 5000

我想要这个:

 empid|2nd max  | max
 1497 | 100000  |  200000
 2000 | 1500    |  5000 
4

2 回答 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

更新
鉴于 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
于 2012-06-27T13:58:52.140 回答
1

您可以在 MySQL 的子句中使用LIMITwith来查找第二个里程。这样您就可以通过不使用昂贵的.OFFSETORDER BYGROUP 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
;
于 2012-06-27T14:02:26.040 回答