Retrieving the most recent entry in a database table with a certain value


I have a table with three fields - userID, couponID, last_couponID.

When the user accesses a coupon, I run this query:

  mysql_query("INSERT INTO users_coupons (userID, couponID) VALUES ('$recordUserID', '$recordCoupID')");

Further, I have another query that should insert the last couponID into the field last_couponID, by polling the database table and finding the most recent result for the current userID.

I believe it is as such:

 SELECT couponID FROM users_coupons ORDER BY userID LIMIT 1

Am I correct? Or should I use a different query?

Like this:

userID   couponID
  1         3
  1        13
  1        23
  2         5
  2         3

So if I wanted userID 2's latest coupon, it'd be '3', and for userID 1, it'd be '23'. I just want the last entry in the database table where the userID matches a value I provide.

I would just add a primary key (autoincrementing) to the users_coupons table.

When you want the latest coupon of a user,
SELECT couponID FROM users_coupons WHERE userID = ? ORDER BY id DESC LIMIT 1