Obtaining the most recent records in a transaction table

advertisements

I'm trying to run a query on a table that we keep for transactions regarding aspects of records of our database. To be more specific, when we "expire" an "asset" (as we call it), we change it's state to expired in the main table, and then record the record of when it was expired in another (this was not my design).

The problem is, sometimes the end user gets impatient with the front-end and we end up with multiple expired transactions for a specific record from the other table.

The table in question is as follows:

+---------------+-----------------------------+------+-----+-------------------+-------+
| Field         | Type                        | Null | Key | Default           | Extra |
+---------------+-----------------------------+------+-----+-------------------+-------+
| m_id          | int(11)                     | NO   | PRI | 0                 |       |
| a_ordinal     | int(11)                     | NO   | PRI | 0                 |       |
| date_expired  | datetime                    | NO   | PRI |                   |       |
| expire_state  | enum('EXPIRED','UNEXPIRED') | YES  |     | NULL              |       |
| note          | text                        | YES  |     | NULL              |       |
| created_by    | varchar(40)                 | YES  |     | NULL              |       |
| creation_date | datetime                    | NO   |     |                   |       |
| updated_by    | varchar(40)                 | NO   |     |                   |       |
| last_update   | timestamp                   | NO   |     | CURRENT_TIMESTAMP |       |
+---------------+-----------------------------+------+-----+-------------------+-------+

From what I can ascertain, m_id, a_ordinal and date_expired form a composite key.

What I need is a query to the table to display the most recent transaction for each expired record (m_id, a_ordinal, expired_date). Currently it's displaying 809 records, but that's because we could have multiple instances of when the record was expired:

|      2223 |      20 | 2011-05-02 12:15:43 | EXPIRED      | 165 Plays. Program quality is poor.
|      2223 |      20 | 2011-05-02 12:16:05 | EXPIRED      | 165 Plays. Program quality is poor.

I know it involves a sub-query with a join, (or perhaps not?) but it's been 5 years since I've worked with MySQL, and I'm very rusty. Any help would be appreciated!!


SELECT t.m_id, t.a_ordinal, t.date_expired, t.note
FROM expiry_table_name t
INNER JOIN  (
    SELECT m_id, a_ordinal, MAX(date_expired) AS date_expired
    FROM expiry_table_name
    GROUP BY m_id, a_ordinal
    ) g
ON g.m_id = t.m_id
AND g.a_ordinal = t.a_ordinal
AND g.date_expired = t.date_expired

n.b. If you have duplicate date_expired values (for a specific m_id, a_ordinal combination) you'll need to do something more sophisticated.