I have a table that records a history of address updates, called transaction. The schema is something like row_id (int, PK), user_id (int), address1 (varchar), transdate (timestamp).
I want to query the table and have a single row returned for a user showing what is the latest row (i.e. greatest timestamp), but if there is data in the address1 column I want the latest row with data. If there is no data in this column then just the latest row.
Example:
row_id user_id address1 transdate 1 70005 56 The Street 2010-08-25 09:15 2 70005 NULL 2010-08-25 10:04 3 70005 12 Some Road 2010-08-25 11:17 4 70005 NULL 2010-08-25 12:18
With a query like
SELECT user_id, address1 FROM transaction t WHERE user_id = 70005 AND row_id = (SELECT MAX(row_id) FROM transaction ti WHERE ti.user_id = t.user_id)
the returned result would be
user_id address1 70005 NULL
but what I want is
user_id address1 70005 12 Some Road
because this is the latest row for that user that has some data.
Hope this makes sense. Does anyone have any suggestions?
I am using MySQL 5.1.49 (community). Thanks.