简体   繁体   中英

Selecting the previous or next row based on ID

I have a mysql table where I want to get the inferior (ie previous) or superior (ie next) item based on the ID of the current selected value.

Like this:

$id_ani = $cap['id_ani']; //Current id
$id_capnex = $cap['id_cap']+1; //Superior id
$nexcap = mysql_query("SELECT * FROM m_table WHERE id_cap=$id_capnex");
$id_caprev =  $cap['id_cap']-1; //Inferior id
$prevcap = mysql_query("SELECT * FROM m_table WHERE id_cap=$id_caprev");

So in the code I have the Current id, Superior id, and Inferior id.

The problem here is that if the current id = 1 and the only existing id after 1 is 4 the Superior id would be '1'+1 instead of 4 which is the only existing id after 1. The same applies if I did it with a inferior one.

Is there a way to select 4 instead of 2 and do the same with the inferior id?

Thanks in advance.

Try to use greater than > or less than <

$id_capnex = $cap['id_cap']+1; //Superior id
$nexcap = mysql_query("SELECT * FROM m_table WHERE id_cap=$id_capnex");
$id_caprev =  $cap['id_cap'];
$prevcap = mysql_query("SELECT * FROM m_table WHERE id_cap<$id_caprev orber by id_cap ASC");
//inferior
$prevcap = mysql_query("SELECT * FROM m_table WHERE id_cap>$id_caprev orber by id_cap ASC");
//superior

As side note i'd add that mysql_* function are deprecated and no longer maintained, so I think it's time to switch either to PDO or mysqli and use prepared statements to avoid any risk of mysql injections , learn more here How can I prevent SQL injection in PHP?

$limit_id=$cap['id_cap']+2

Using bellow Query, you can get prev and next . The result of this query will returns two rows . first one is previous and other one is next.

SELECT * , IF( id >$cap['id_cap'], 1, 0 ) AS NextFlag, IF( id <$cap['id_cap'], 1, 0 ) AS PrevFlag FROM m_table 
WHERE id_cap <$limit_id
HAVING NextFlag =1
OR PrevFlag =1
ORDER BY id_cap DESC
LIMIT 2 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM