thestars Posted July 8, 2009 Share Posted July 8, 2009 How can I get the very next Primarykey and just previous Primarykey of a given row using mysql query?Please help me Quote Link to comment https://forums.phpfreaks.com/topic/165164-mysql-query-to-get-next-previous-id/ Share on other sites More sharing options...
JonnoTheDev Posted July 8, 2009 Share Posted July 8, 2009 SELECT MAX(fieldname) AS lastPK, MAX(fieldname)+1 AS newPK FROM table Quote Link to comment https://forums.phpfreaks.com/topic/165164-mysql-query-to-get-next-previous-id/#findComment-870876 Share on other sites More sharing options...
thestars Posted July 8, 2009 Author Share Posted July 8, 2009 Hi, In database, the IDs may be in random order and the difference between the two IDs may not be 1. IDs will be like 1, 3, 4, 33, 10 etc. So , I need 10 if current ID is 4. Hope you got it. Quote Link to comment https://forums.phpfreaks.com/topic/165164-mysql-query-to-get-next-previous-id/#findComment-870879 Share on other sites More sharing options...
JonnoTheDev Posted July 8, 2009 Share Posted July 8, 2009 SELECT id FROM table ORDER BY id DESC LIMIT 2 This will give you the last 2 records Quote Link to comment https://forums.phpfreaks.com/topic/165164-mysql-query-to-get-next-previous-id/#findComment-870882 Share on other sites More sharing options...
thestars Posted July 8, 2009 Author Share Posted July 8, 2009 But this will give only the last two records. Quote Link to comment https://forums.phpfreaks.com/topic/165164-mysql-query-to-get-next-previous-id/#findComment-870885 Share on other sites More sharing options...
JonnoTheDev Posted July 8, 2009 Share Posted July 8, 2009 How can I get the very next Primarykey and just previous Primarykey of a given row using mysql query? OK if you want the next and prev record from a given row just us > < opeartors // next row SELECT id FROM table WHERE id > 123 ORDER BY id ASC LIMIT 1 // prev row SELECT id FROM table WHERE id < 123 ORDER BY id DESC LIMIT 1 Quote Link to comment https://forums.phpfreaks.com/topic/165164-mysql-query-to-get-next-previous-id/#findComment-870890 Share on other sites More sharing options...
thestars Posted July 8, 2009 Author Share Posted July 8, 2009 Thank you so much Neil. Its working !!!! . I got the correct answer. Thanks Quote Link to comment https://forums.phpfreaks.com/topic/165164-mysql-query-to-get-next-previous-id/#findComment-870894 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.