Check if row in database exists, otherwise, restart query again

0

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

I'll get a news, and on this page has a link to the previous news, and I'll search for it by searching for the current news id - 1, but in this way, it will go to ids that may not exist or have been deleted , is there a way to ignore the empty ones and do the query again?

    
asked by anonymous 22.09.2017 / 19:09

2 answers

0

From what I understand you want to get the latest news before the news that you are. If you use the ID as Sequential Integer to do something like:

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

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

    
22.09.2017 / 19:16
0

You can search based on the current ID and limiting the record 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 notice 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
    
22.09.2017 / 19:40