I have a table that tracks serial numbers and the number of licenses associated with said serial number. A client can re-license a box, increasing or decreasing the number of users, and they are only billed for the changed amount.
The following table structure exists:
id - Auto Incrementing ID
serial - The serial number
numusers - the number of licenses
date - The date that the request was submitted, with the highest date being the number of users currently licensed
I have the following query to select the licenses that have been updated, and it works if the license has only been resubmitted once. If it has been resubmitted more than once, it returns references to the previous update, and all updates before that.
SELECT p.id as id, c.id as oldid, p.numusers-c.numusers AS dif, p.date, c.date
FROM `licenses` AS p
JOIN `licenses` AS c ON p.serial = c.serial
AND p.date > c.date
AND p.id <> c.id
WHERE p.id = 156
#GROUP BY p.id
Here is the dataset:
id serial numusers date
26 1234 500 2010-07-14
34 1234 600 2010-07-15
156 1234 500 2010-07-21
When I run the query, I get the following:
id oldid dif date date
156 26 0 2010-07-21 2010-07-14
156 34 -100 2010-07-21 2010-07-15
If I uncomment the GROUP BY clause in the query, I get the row with the oldid of 26. How would I only select the row with the most recent date (row with oldid of 34)? I could use ORDER BY and LIMIT 1, but I also want to be able to select from the whole table without the WHERE clause.
I am using MySQL 5.1.