开发者

Efficient way of getting Last ID in database without inserting?

I have this table (table1):

id = 1  , color = red
id = 2 , color = blue

How do I find the color value from last id inserted? Is it simply:

SELECT * FROM ta开发者_运维问答ble1 ORDER BY id DESC limit 1  

and then get the colour? Is there a more efficient way? instead of select *, just tell it go to last row and find the colour?

I can't use last insert, because I'm not inserting anything.

$id = $db->lastInsertId();


if you only need the value of color column, then select just that

SELECT color FROM table1 ORDER BY id DESC limit 1


Actually the query you wrote is correct. The sql engine will go to the last record and take it. It will not sweep the whole table so you do not have to worry about performance.


SELECT id, color FROM table1 ORDER BY id DESC limit 1

will give the last id and it's color (the '*' means all columns, not all rows)


Since ID is not only indexed, but the primary key, this is an efficient operation. If you were to use it on a non-indexed column, you might get a performance problem. LAST_INSERT_ID() is an option too, but only works if the row was inserted during the current session.


If id is autoincremented, this query:

SELECT  *
FROM    table1
WHERE   id = LAST_INSERT_ID()

will return you the color last inserted in the current session (unless you inserted into other autoincrementing tables in between)

If you need the last value overall (not only in the current session), then your query is fine.

SELECT  color
FROM    table1
ORDER BY
        id DESC
LIMIT 1  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜