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 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 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. 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 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. 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 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 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
Archived
This topic is now archived and is closed to further replies.