使用MAX date来JOIN表并获取列值

时间:2017-10-26 20:16:01

标签: mysql sql max

我正在尝试从客户最近的订单中获取跟踪号,但我在使用MAX时遇到了问题。

这只是一直没有返回,即使我知道table2中有值的日期。我的查询出了什么问题?

SELECT
    t1.Invoice_Num,
    t1.Tracking_Num
FROM
    table1 t1

JOIN
    table2 t2a on t1.Invoice_Num = t2a.Invoice_Num
JOIN (
    SELECT
        t2b.Invoice_Num,
        MAX(t2b.Invoice_Date) Last_Sale
    FROM
        table2 t2b
    WHERE
        t2b.Customer_Num = 'cust1'
    GROUP BY t2b.Invoice_Num
) LS
on t1.Invoice_Num = LS.Invoice_Num

--------------------------------------------------

Table1
+-------------+--------------+
| Invoice_Num | Tracking_Num |
+-------------+--------------+
| abc123      |     12345678 |
| def456      |     87654321 |
+-------------+--------------+

Table2
+-------------+--------------+--------------+
| Invoice_Num | Customer_Num | Invoice_Date |
+-------------+--------------+--------------+
| abc123      | cust1        | 10/25/2017   |
| def456      | cust1        | 10/24/2017   |
+-------------+--------------+--------------+

所需的输出是 -

+-------------+--------------+
| Invoice_Num | Tracking_Num |
+-------------+--------------+
| abc123      |     12345678 |
+-------------+--------------+

基于Invoice_Date

的最新cust1

2 个答案:

答案 0 :(得分:1)

这是一种可以派上用场的通用替代方法:

使用ORDER BY .. DESCLIMIT 1

SELECT
       t1.Invoice_Num,
       t1.Tracking_Num
FROM table1 t1
JOIN table2 t2 USING(Invoice_Num)
WHERE t2.Customer_Num = 'cust1'
ORDER BY t2.Invoice_Date DESC
LIMIT 1

SQL Fiddle

答案 1 :(得分:0)

SQL DEMO

SELECT
    t1.Invoice_Num,
    t1.Tracking_Num
FROM table1 t1    
JOIN table2 t2 
  ON t1.Invoice_Num = t2.Invoice_Num
JOIN ( SELECT  MAX(t2b.Invoice_Date) Last_Sale
       FROM table2 t2b
       WHERE t2b.Customer_Num = 'cust1'
     ) LS
  ON t2.Invoice_Date = LS.Last_Sale

小心,因为如果多行共享最后一笔销售,您将获得多行。