Suppose there is a table with a "title" column and the following entries:

id title 1 Заголовок 4 2 Заголовок 2 3 Заголовок 1 4 Заголовок 3 

Type of required sorting: alphabetically (title field).

Tell me, is it possible to get "previous" and "next" records with the help of requests, i.e. for "header 2" the previous one will be the record "header 1", and the next one will be the record "header 3"?

I see one way to do full requests:

 SELECT * FROM table ORDER BY title 

get an array of this sample and then in PHP find the current header and get the previous / next element of the array.

  • And what is the condition of the sample? By primary key or by title title? - Deonis
  • Condition - by title title. The site has a list of products, sorted by name. It is necessary to make the transition "to the next" and "to the previous" product. The primary key is the identifier (additional field), i.e. here it will not work. - korwru
  • Save the field header name in a variable (REMEMBER !!! there is no “column” concept in databases - there is a “FIELD” and “RECORD”, but here you are right :)). Create two variables, say, strPrev and strNext. Further, respectively, when you click a button (links, menu ...) "Next" - you remember the current title in the variable strPrev and vice versa. Request to generate an elementary: select * where title = ... {variable name} - Vyacheslav Kirichenko
  • Table: id title 1 Title 3 2 Title 1 3 Title 2 4 Title 4 I will make the query SELECT * WHERE title = "Title 1" and I can not do anything with the selection ... :) - korwru
  • one
    Monsieur understands perversions. There is a question: id go in a row, i.e. idPrev = id-1, idNext = id + 1 (option 1) or not (option 2)? - alexlz

2 answers 2

  1. To number the lines, for example, like this .
  2. For the line with the number N, take the lines with the numbers N-1 and N + 1.

    Everything turned out just ...

     SELECT * FROM `table` WHERE title < 'Заголовок 2' ORDER BY title DESC LIMIT 1 SELECT * FROM `table` WHERE title > 'Заголовок 2' ORDER BY title LIMIT 1