简体   繁体   English

Mysql表中的最后一条记录

[英]Last Record in a Mysql Table

I have a Dynamic table like this 我有这样的动态表

Product_id  Product_name  

1            Mobile Phone
5            Computer
3            Mobile Phone

I need a query to find the last record(latest record) in a table. 我需要查询以查找表中的最后一条记录(最新记录)。

If your ProductID column is always incrementing, and the last record is the one with the maximum product ID then you can use this: 如果您的ProductID列始终在递增,而最后一条记录是具有最大产品ID的记录,则可以使用以下记录:

SELECT * FROM tablename
ORDER BY Product_ID DESC
LIMIT 1

You would probably want to create an index on your table which sorts the table according to what you want for best performance and easy querying. 您可能希望在表上创建一个索引,该索引会根据所需的内容对表进行排序,以实现最佳性能和轻松查询。 If the latest added item in your table is getting the highest ID, then you want to create an index on the ID's. 如果表中最新添加的项目获得最高ID,则您要在ID上创建索引。 Fx: 外汇:

CREATE INDEX index_name ON table_name (Product_id)

When you have a table and your index, then you would want to write something like 当您有一个表和您的索引时,那么您将需要编写类似

SELECT Product_name FROM table_name DESC LIMIT 1;

in order to get the latest added item. 为了获得最新添加的商品。

You can store the last insert id in a variable and insert in to another table 您可以将最后一个插入ID存储在变量中,然后插入另一个表中

 SET @last_id_in_table1 = LAST_INSERT_ID();
        INSERT INTO table2 (parentid,otherid) VALUES (@last_id_in_table1,1); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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