0

我有 2 个表,例如CustomersOrders在表中Customers我有列idname在表中我Orders有列id,,customer_idorder_date

现在我需要做出一个选择,它将返回每个 Customer'sidname最后一个order_date

我试着做这样的:

select
    Customers.id,
    Customers.name,
    (select Orders.order_date from Orders where Orders.customer_id = Customer.id order by order_date desc) as last_order_date
from
    Customers

但是它得到了错误的索引并且需要永远执行。在 PostgreSQL 中进行此选择的最佳方法是什么?

先谢谢了。

4

1 回答 1

2

如果不限制 by customer_id,则查询最终将不得不扫描整个订单表。

SELECT c.id
      ,c.name
      ,MAX(o.order_date) AS last_order_date
FROM Customers c
LEFT OUTER JOIN Orders o ON (o.customer_id = c.id)
GROUP BY c.id, c.name
于 2013-01-12T14:32:52.920 回答