开发者

how to select the last value entered to a column of a db table [closed]

开发者 https://www.devze.com 2023-01-14 14:48 出处:网络
开发者_Go百科It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. F
开发者_Go百科 It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

someone plz give me the query to select the last value entered to a column of a table of a sql database....


In general after inserting a row into a table, you want to immediately retrieve and store the last insert id.

Then simply do a select * where id=<the last insert id>.

MySQL documentation on last insert id

However in the case where you need to retrieve the last insert'ed row for a row that was inserted at a previous point in time (and the last_insert_id is not available) you have two main options:

  • If there is a unique auto-incrementing ID field, select the row with the highest ID
  • Have a date/time or timestamp field in the table that records exactly when a row is inserted. Then simply select the row with the latest date/time value.


You should have a mechanism first of all to identify which row was inserted when, or at least which row was inserted after a certain row. Your best choice is to have a auto incrementing field or a timestamp.

Once that is figured out, it is actually a simple process

You have not specified the database, so assuming it is SQL Server,

For auto incrementing id

SELECT TOP 1 *ColumnYouWant* FROM *TableYouWant* [Where Clauses If You Want] ORDER BY *AutoIncrementingField* DESC

For Time Stamps

SELECT TOP 1 *ColumnYouWant* FROM *TableYouWant* [Where Clauses If You Want] ORDER BY *TimeStampField* DESC

For MySQL

SELECT *ColumnYouWant* FROM *TableYouWant* [Where Clauses If You Want] ORDER BY *AutoIncrementingField* DESC LIMIT 0,1

Please correct me if I am wrong :)

0

精彩评论

暂无评论...
验证码 换一张
取 消