我正在尝试从表格中选择最大里程和第二大里程。
到目前为止,我的查询是:
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
但这会选择输入的第一个里程和最大值。
我如何改变它以获得第二大里程?
我正在尝试从表格中选择最大里程和第二大里程。
到目前为止,我的查询是:
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
但这会选择输入的第一个里程和最大值。
我如何改变它以获得第二大里程?
基本上做一个正常的查询,并按降序排序并限制为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
一种快速而肮脏的方法是排序
ORDER BY oil.mileage DESC
接着
LIMIT 0, 2
试试这个:如果你只需要倒数第二个里程然后使用这个::
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
如果您同时需要最大值和倒数第二个,请使用此::
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