简体   繁体   中英

Select last 2 record against record ID in SQL

I want to know if there is a query for selecting last two inserted records against record ID.

For example we can select only 1 top record by using this query:

select max(colName) from tableName

But what query could be for this:

select "Last two records of" colName where id = 1

so if we have 100 records in the table and we have 10 records against id number 1, then we should get the last two inserted records against the id number 1.

Please help me if anybody understood my question.

Note: id is not unique key OR primary key in the table from where I want to get the record.

Script should be something like below-

SELECT TOP 2 * 
FROM tableName
WHERE id = 1
ORDER BY colName DESC

what about

select colName from tablename where id in (x,x-1)

Assuming you are using auto increment for the primary key

if you have the column, created_at you can do something like

select * from table where id = 1 order by created_at desc limit 2

that should give you the most recent inserted elements. Are you using postgres, mysql, oracle?

select top (2) * from <myTable> where id = 1 order by id DESC

这将返回最后2个插入的行,其中Id = 1

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