tags:

views:

62

answers:

3

The last InvoiceID, and corresponding fields needs to be selected. The entire sql contains several inner joins.

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

Right now, I am getting the InvoiceID, and have to fetch the InvoiceEndDate again.

Is there an efficient way of doing this?

+4  A: 
SELECT InvoiceID, InvoiceEndDate 
FROM Invoices 
WHERE TransactionOrderItemID='000831'
ORDER BY InvoiceID DESC
LIMIT 1
David Hedlund
Glad I saw that. If that works, it's way easier than the way I was going to suggest...
Kendrick
OP says MySQL, so LIMIT 1 would be needed after the order by instead of TOP 1 before the select list.
martin clayton
@martin: good catch =)
David Hedlund
A: 
SELECT InvoiceID, InvoiceEndDate 
FROM Invoices INV
WHERE TransactionOrderItemID='000831'
  AND INV.InvoiceID = (SELECT MAX(SUB.InvoiceID)
    FROM Invoices SUB WHERE SUB.TransactionOrderItemID='000831');
FelixM
A: 

Take a look at Including an Aggregated Column's Related Values which has several ways to accomplish this

SQLMenace
Okay didn't know it was MySQL...I saw TOP in the first answer and assumed it was SQl Server
SQLMenace