MySQL - 根据时间戳加入最新订单的订单号

时间:2016-01-22 16:27:12

标签: mysql sql

我从customers表中选择一个客户并尝试从jobs表中获取客户的最新订单号,但是基于该表中的不同时间戳列。

客户

id  |  name | ...

工作

id  | customer_id  |  order_id | assigned
----------------------------------------------------
1   | 985          |  8020     | 2015-12-03 00:00:00
2   | 985          |  4567     | 2015-04-19 00:00:00
3   | 985          |  9390     | 2016-20-01 00:00:00
4   | 985          |  6381     | 2015-08-26 00:00:00

应加入的最新order_id 9390 ,因为assigned时间戳是最新的。

SQL

SELECT c.name, j.latest_order
FROM customers c
LEFT JOIN (
    SELECT customer_id,
           ??? AS latest_order
    FROM jobs
    WHERE withdrawn IS NULL
    GROUP BY customer_id
) j ON j.customer_id = c.id
WHERE c.id = 985

我无法确定在子查询中获取latest_order的最佳方法,但它应该是该客户的jobs.order_id jobs.assigned = MAX(jobs.assigned)

3 个答案:

答案 0 :(得分:0)

使用另一个派生表来获取最新订单的订单号。

SELECT c.name, t.order_id, j.latest_order
FROM customers c
JOIN (
    SELECT customer_id,
           max(assigned) AS latest_order
    FROM jobs
    WHERE withdrawn IS NULL
    GROUP BY customer_id
) j ON j.customer_id = c.id 
JOIN (select customer_id, order_id, assinged 
      from jobs 
      where withdrawn is null) t
    ON t.customer_id = j.customer_id and t.assigned = j.latest_order
WHERE c.id = 985

答案 1 :(得分:0)

我不确定这是否是最快的方式,但也许你想尝试解释替代答案来比较两种表现:

SELECT c.name, j.latest_order
FROM customers c
LEFT JOIN (
  SELECT j1.customer_id, j1.order_id 
  FROM jobs j1 
  JOIN (
    SELECT customer_id, max(assigned) as maxassigned
    FROM jobs j2
    WHERE withdrawn IS NULL
    GROUP BY customer_id
  ) j2
  ON j1.customer_id = j2.customer_id and j1.assigned = j2.maxassigned) j
ON j.customer_id = c.id
AND c.id = 985;

答案 2 :(得分:0)

正如您已经了解customer_id,您可以通过更简单,更短的方式实现这一目标。您只需选择该客户的所有订单,按日期排序并仅返回第一条记录。

以下是查询:

SELECT r.name, r.order, r.assigned
FROM (
    SELECT c.name AS name, j.order_id AS order, j.assigned AS assigned
    FROM customer c
    INNER JOIN jobs j
    ON AND c.id = j.customer_id
    WHERE c.id = 985 AND j.withdrawn IS NULL) r
ORDER BY r.assigned DESC
LIMIT 1