简体   繁体   English

同时选择倒数第二个mysql值

[英]Also select second to last mysql value

I am trying to select the max mileage and the second biggest mileage from a table. 我正在尝试从表中选择最大里程和第二大里程。

my query so far is: 到目前为止,我的查询是:

SELECT oil.empid, oil.mileage, users.name, oil.date, MAX(oil.mileage)
FROM oil, users
WHERE oil.empid = users.empid
GROUP BY oil.empid
ORDER BY oil.mileage

but this selects the first mileage entered and the max. 但这会选择输入的第一个里程和最大里程。

how do i change this to get the second biggest mileage? 我该如何更改以获得第二大里程?

Basically do a normal query and sort it descending and limit it by 2. Something like the below (not tested) 基本上执行普通查询并对其进行降序排序,并限制其为2。类似下面的内容(未经测试)

SELECT
    oil.empid,
    oil.mileage,
    users.name,
    oil.date
FROM oil, users
WHERE (oil.empid = users.empid)
GROUP BY oil.empid
ORDER BY oil.mileage DESC
LIMIT 2

Try this: IF U need only the second last mileage then use this:: 尝试以下操作:如果U仅需要倒数第二个里程,请使用以下命令:

SELECT oil.empid, oil.mileage, users.name, oil.date, MAX(oil.mileage)
FROM oil, users
WHERE oil.empid = users.empid
GROUP BY oil.empid
ORDER BY oil.mileage desc
limit 1, 1

If u need both the max as well as the second last use this:: 如果您同时需要最大值和倒数第二个,请使用以下命令:

SELECT oil.empid, oil.mileage, users.name, oil.date, MAX(oil.mileage)
FROM oil, users
WHERE oil.empid = users.empid
GROUP BY oil.empid
ORDER BY oil.mileage desc
limit 2

A quick and dirt way to do it is to sort 一种快速而肮脏的方法是排序

ORDER BY oil.mileage DESC

and then 接着

LIMIT 0, 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM