Check if line in database exists, if not, restart query again

Asked

Viewed 41 times

0

I have a database and would like to always fetch the value before, and I have used for example:

I will fetch a news, and on this page there is a link to the previous news, and I will search for the id of the current news - 1, but this way, it will for ids that may not exist or have been deleted, there is way to ignore the gaps and query again?

  • You can search on the condition that the id is smaller than the current one and limit it to the first record. For example: SELECT * FROM noticias WHERE id < 3 ORDER BY id DESC LIMIT 1 -- Previous

2 answers

0


From what I understand you want to get the latest news before the news you’re on. If you use the ID as sequential Integer from to do something like:

  SELECT columns FROM noticias WHERE id < 'id_noticia_atual' ORDER BY id DESC LIMIT 1

Basically you will search for the last ID before your current news and then search for the news according to the id you found.

0

You can search based on current ID and limit registration amount.

Ex:

SELECT * FROM noticia WHERE id < 3 ORDER BY id DESC LIMIT 1 -- Essa seria a noticia anterior
SELECT * FROM noticia WHERE id > 3 ORDER BY id LIMIT 1 -- Essa seria a próxima

You can also do everything in a query. In Postgres for example, you can bring each news in a column with a json.

Ex:

select to_json(noticia) as atual,
       to_json((
                 SELECT noticia
                 FROM noticia
                 WHERE id < 2
                 ORDER BY id DESC
                 LIMIT 1
       )) as anterior,
       to_json((
                 SELECT noticia
                 FROM noticia
                 WHERE id > 2
                 ORDER BY id
                 LIMIT 1
       )) as proxima
from noticia
where id = 2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.