简体   繁体   中英

find entries to the left and right of a certain entry in a mysql table in a single query

Let's say I have a table in a database like this table . Let's say that I want to get the entries on the left and right of the entry whose the primary key is equal to 5 (or any other primary key). So in our case, I want to get the entries whose primary key is equal to 4 and 6 respectively. What is the SQL query that will give me such result? Can you guys translate the SQL query into a find('all') CakePHP query?

Thank you

NOTE: The ids are not necessarily contiguous, meaning, they do not necessarily follow the 1, 2, 3, 4, 5, 6, 7, 8 sequence. I can have something like 1, 5, 13, 44, 66, 123, etc

Try Union like this

 (SELECT * FROM employee WHERE id < 5 order by id DESC LIMIT 1)
 UNION
 (SELECT * FROM employee WHERE id >5  LIMIT 1)

PHP

$id = 5;
SELECT * FROM Employee where id = $id-1 OR id = $id+1;

MySQL

SET @id = 5;
SELECT * FROM Employee where id = @id-1 OR id = @id+1;

Checkout find('neighbors') . It returns the records before and after the one you specify and your ids can have "holes" in the sequence.

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