有两个表:
我想使用以下查询查找第二笔最高付款的客户:
select name, min(pay) from
(select a.name as 'name', sum(b.payment) as 'pay'
from customer a join payment b
using(customer_id) group by a.name
order by sum(b.payment) desc limit 2)as T;
衍生表格:
name pay
name1 200
name2 100
实际结果:
name2 100
我得到的结果:
name1 100
外部查询正在提取工资金额,但名称错误
答案 0 :(得分:1)
您得到的结果对于最低工资是正确的,但是您得到的名称不明确。
您所要做的就是对子查询中升序的2行进行重新排序,仅获得第一行:
select t.name, t.pay from (
select a.name as name, sum(b.payment) as pay
from customer a inner join payment b
on b.customer_id = a.customer_id
group by a.name
order by sum(b.payment) desc
limit 2) t
order by t.pay
limit 1;
在您的代码中,我猜同一列有两个名称:payment
和amount
。
我在代码上方使用了payment