sophie
sophie

Reputation: 1521

How can I SELECT the last row that NO ID increment

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'sNO an auto_incrementin that table.

And my case is to update the existing last row in table and then insert a new one.

Upvotes: 1

Views: 1531

Answers (2)

jcho360
jcho360

Reputation: 3759

if you don't have order by you wont be able to get the "LAST" value or the first, because the order will not be the same (necessarily), if you don't have auto increment how can you know which one is the first or the last?, if you are working with date or auto increment you will be able to get that, however, lets say that you have a order by 'column1' you can do something like:

select * from table1 order by `column1` desc limit 1

Upvotes: 1

cichy
cichy

Reputation: 10644

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 )

Upvotes: 6

Related Questions