我试图从桌子上选择最大里程数和第二大里程数。
到目前为止我的查询是: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
但是这会选择输入的第一个里程和最大值
我如何改变它以获得第二大里程?
答案 0 :(得分:1)
基本上做一个普通的查询并按降序排序并将其限制为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
答案 1 :(得分:0)
试试这个: 如果你只需要倒数第二个里程,那么使用这个::
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
如果你同时需要max和second second,请使用::
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
答案 2 :(得分:0)
快速而肮脏的方法是排序
ORDER BY oil.mileage DESC
然后
LIMIT 0, 2