如何在内连接中选择第二个最小值?

时间:2016-09-02 04:15:32

标签: mysql subquery max inner-join min

我有这个查询

select c.id, c.name, c.email, c.totalpets, min(p.date_created) as first_order,
min(p.weight) as min_weight_bought,
max(p.weight) as max_weight_bought,
count(p.ordernumber) as total_orders
from orders p
inner join customers c
on p.customer_id = c.id
where p.approved = 1
and c.totalpets >= 1
group by c.id
having total_orders > 1

请注意,first_order为我提供了该行的第一个结果,对吧?我正在努力获得客户第一笔订单和客户第二笔订单。我怎么能在这个内部联接中做到这一点?

由于

1 个答案:

答案 0 :(得分:1)

SELECT c1.id,
       c1.name,
       c1.email,
       c1.totalpets,
       p1.date_created
FROM orders p1
INNER JOIN customers c1
    ON p1.customer_id = c1.id
WHERE 
(
    SELECT COUNT(*)
    FROM orders p2
    INNER JOIN customers c2
        ON p2.customer_id = c2.id
    WHERE c2.id = c1.id AND p2.date_created <= p1.date_created
) <= 2 
ORDER BY c1.id;

这是一个正在运行的演示,它显示了上述查询(和简化数据集)的简化版本:

SQLFiddle