2009-12-04 60 views
0

需要選擇最後一個InvoiceID和相應的字段。整個sql包含幾個內部連接。SQL - 選擇最大ID字段

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

現在,我正在InvoiceID,並有再次讀取該InvoiceEndDate。

有沒有這樣做的有效方式?

回答

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

很高興我看到了。如果這樣做,它比我建議的方式更容易... – Kendrick 2009-12-04 18:11:42

+2

OP說MySQL,所以限制1將需要在順序之後,而不是選擇列表之前的TOP 1。 – 2009-12-04 18:14:02

+0

@martin:good catch =) – 2009-12-04 18:18:36

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