How can I SELECT the last row in a MySQL table?
I'm INSERTING data and I need to retrieve a column value from the previous row.
(I'm using PHP by the way.) the table1 something like this
table1
******************
cate_id | task_id | start_date | end_date | line |
1 2 30/04/2012 26/06/2012 text
3 1 26/06/2012 27/06/2012 text
2 1 27/06/2012 01/01/9999 text
There's NO an auto_increment
in that table.
And my case is to update the existing last row in table and then insert a new one.
You've edited question so, here's update
SELECT MAX(cate_id) AS last_cate_id FROM table;
or you can get next ID by:
SELECT MAX(cate_id)+1 AS next_cate_id FROM table;
Without transactions this is very vulnerable for inserting same cate_id!
If you cant use them, for example because of MyISAM, you could insert with select.
INSERT INTO table
(cate_id, task_id ..)
VALUES
( (SELECT MAX(cate_id)+1 AS next_cate_id FROM table), 1 )
如果您没有订单,您将无法获得“ LAST”值或第一个值,因为订单将是不同的(必要),如果您没有自动递增功能,那么如何知道哪一个是第一个还是最后一个?,如果您正在处理日期或自动递增,您将能够得到它,但是,假设您有一个按'column1'
排序的订单,则可以执行以下操作:
select * from table1 order by `column1` desc limit 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.