简体   繁体   中英

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

Assuming that couponID is numeric, and the last couponID for a certain userId is the greatest (as a number), you can do:

SELECT MAX(couponID) AS lastCouponId FROM users_coupons WHERE userId = <put here the user id>

EDIT: since you've edited your question, I edit my answer.

You have to add an auto-increment primary key, otherwise you can't know exactly which entry is the last one. When I answered, I supposed the last coupon for a certain userId was the one with the greatest couponId . Are you sure you can't just make things work this way?

Something along the lines of...

SELECT couponID
FROM users_coupons
WHERE userID = <current user id>
ORDER BY <primary key of user_coupons table if it's an identity column> DESC
LIMIT 1

...is more appropriate. Your query as it stands doesn't do anything with the 'current' user ID.

If you are actually after the highest couponID then SELECT MAX(couponID)... as suggested by Giacomo is a good idea - coupled with a check for the UserID matching the current user ID.

@Giacomo's answer is valid if you are incrementing the CouponID reliably as an identifier. If you have merged in data or are adjusting this value any other way then it may not be correct.

In theory, if you consider CouponID to be a surrogate key then you cannot use it to explicitly determine insert order. If you intend for it to be used for the purpose of insert order then you also need to make sure your supporting code and DB maintenance plans promote this use.

I contend that the "correct" method is to also store a DateTime

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM