Dear All,
I have a query as below SELECT DISTINCT (productID),totalAmountAfter,transactionDate FROM tbltransaction WHERE transactionDate BETWEEN '2010-01-01' AND '2010-12-31' ORDER BY productID,transactionDate DESC .
My problem now I want is that for each product only pick one line that is the last line since I have ordered by the date. But even using distinct I still get a more than one data for each productID. Any solution for this?
newbie14
0
Posting Pro
Recommended Answers
Jump to Postbecause the combination containing productid, totalAmountAfter, transactionDate is what the distinct applies to, not just the productID,
Jump to PostAlong those lines:
SELECT productID,totalAmountAfter,transactionDate FROM tbltransaction WHERE transactionDate BETWEEN '2010-01-01' AND '2010-12-31' and (productID, transactionDate) in (SELECT productID, max(transactionDate) from tbltransaction group by productID) ORDER BY productID,transactionDate DESC
Jump to PostSet an index on transactionDate.
Study the output of EXPLAIN <thequery> for optimisation hints.
How often do you have to run the query, anyway? Maybe you are better of by caching the result instead of optimizing the run-time behaviour of the query.
Jump to PostLooks like you don't have an index on productID. Isn't that your primary key? Show the output of CREATE TABLE tbltransaction
Jump to PostSet an index on productID. Test with the EXPLAIN <query> statement if it is used by the query optimiser.
Other indexes which are not used by query optimisation are irrelevant - it does not harm to keep them.
All 17 Replies
drjohn
56
Posting Pro in Training
newbie14
0
Posting Pro
smantscheff
265
Veteran Poster
newbie14
0
Posting Pro
smantscheff
265
Veteran Poster
newbie14
0
Posting Pro
smantscheff
265
Veteran Poster
newbie14
0
Posting Pro
smantscheff
265
Veteran Poster
newbie14
0
Posting Pro
voidyman
0
Newbie Poster
newbie14
0
Posting Pro
voidyman
0
Newbie Poster
newbie14
0
Posting Pro
voidyman
0
Newbie Poster
newbie14
0
Posting Pro
smantscheff
265
Veteran Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.