Query to select newly added records only

試著忘記壹切 提交于 2019-12-10 18:55:58

问题


As I am new to mysql, let me clear this doubt. how to write a query to find/select the latest added records only?

Example: Consider a Table, which is daily added certain amount of records. Now the table contain 1000 records. And the total 1000 records are taken out for some performance. After sometimes table is added 100 records. Now I would like take the remain 100 only from the 1100 to do some operation. How to do it?

(For example only, I have given the numbers, But originally I don't know the last updated count and the newly added)

Here My table contain three columns Sno, time, data. where Sno is indexed as primary key.

Sample table:

| sno | time                | data    |

|   1 | 2012-02-27 12:44:07 |     100 |

|   2 | 2012-02-27 12:44:07 |     120 |

|   3 | 2012-02-27 12:44:07 |     140 |

|   4 | 2012-02-27 12:44:07 |     160 |

|   5 | 2012-02-27 12:44:07 |     180 |


|   6 | 2012-02-27 12:44:07 |     160 |

|   7 | 2012-02-28 13:00:35 |     100 |

|   8 | 2012-03-02 15:23:25 |     160 |

回答1:


Add TIMESTAMP field with 'ON UPDATE CURRENT_TIMESTAMP' option, and you will be able to find last added or last edited records.

Automatic Initialization and Updating for TIMESTAMP.




回答2:


Create table as below

Create table sample
(id int auto_increment primary key,
time timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
data nvarchar(100)
);

then query as

select * from sample order by time desc limit 1


来源:https://stackoverflow.com/questions/9531628/query-to-select-newly-added-records-only

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!