对标题感到抱歉。那是我能想到的最好的。
无论如何,这是我的问题 - 我有2个表,一个Customer表和Order表,如下所示:
Customer {
Long id;
String name;
String address;
Timestamp createdOn;
}
Order {
Long id;
String productName;
Long customerId;
Timestamp createdOn;
}
从客户到订单之间存在一对多关系,即客户可以拥有由'customerId'标识的许多订单。
现在这是我的问题。我希望检索所有客户的列表以及他们的最新订单。根据上表,这是我迄今为止能够提出的:
SELECT *
FROM CUSTOMER AS CUSTOMERS
INNER JOIN (
SELECT *
FROM ORDER AS BASE_ORDERS
INNER JOIN (
SELECT MAX_ORDERS.CUSTOMERID,
MAX(MAX_ORDERS.CREATEDON)
FROM ORDER AS MAX_ORDERS
GROUP BY CUSTOMERID
) AS GROUPED_ORDERS
ON BASE_ORDERS.CUSTOMERID = GROUPED_ORDERS.CUSTOMERID
AND BASE_ORDERS.CREATEDON = GROUPED_ORDERS.CREATEDON
) AS LATEST_ORDERS
ON CUSTOMERS.ID = LATEST_ORDERS.CUSTOMERID
有更好的方法吗?我能想到的另一种方法是添加一个名为“isLatest”的新字段,并在每次为客户下达新订单时将其设置为true。
让我知道你的想法。
答案 0 :(得分:1)
我发现这种变化更加清晰:
select c.*, o.*
from (
select customerid, max(createdOn) as MaxCreatedOn
from Order
group by customerid
) mo
inner join Order o on mo.customerid = o.customerid and mo.MaxCreatedOn = o.createdOn
inner join Customer c on o.customerid = c.id
答案 1 :(得分:0)
这样的事情:
SELECT
c.*,
o.*
FROM
Customers c
INNER JOIN
Orders o ON o.customerId = c.id
GROUP BY
c.id
ORDER BY
o.createdOn DESC
不确定Group和Order By语句的效率如何,但我相信它会为您提供您正在寻找的数据。