SQL - 选择最大ID的字段

时间:2009-12-04 18:03:40

标签: sql mysql

需要选择最后一个InvoiceID和相应的字段。整个sql包含几个内连接。

SELECT max(InvoiceID), 
       InvoiceEndDate 
  FROM Invoices 
 WHERE TransactionOrderItemID = '000831'

现在,我收到了InvoiceID,并且必须再次获取InvoiceEndDate。

有没有一种有效的方法呢?

3 个答案:

答案 0 :(得分:4)

SELECT InvoiceID, InvoiceEndDate 
FROM Invoices 
WHERE TransactionOrderItemID='000831'
ORDER BY InvoiceID DESC
LIMIT 1

答案 1 :(得分:0)

SELECT InvoiceID, InvoiceEndDate 
FROM Invoices INV
WHERE TransactionOrderItemID='000831'
  AND INV.InvoiceID = (SELECT MAX(SUB.InvoiceID)
    FROM Invoices SUB WHERE SUB.TransactionOrderItemID='000831');

答案 2 :(得分:0)

看看Including an Aggregated Column's Related Values,它有几种方法可以实现这个目标