önceki - mysql sonraki sorgu

3 Cevap php

I have a table in database that is having unique id's. I have a page where one particular id is shown and link is given for next and previous id's. I have to get those prev and next id's by one single mysql query .All i have is that particular id on whose data we are currently working on. id's are not consecutive numbers as sometimes some id's get deleted also.(for eg. 1,2,3,7,9,10,15 etc)

Peki nasıl ben tek sorguda bu iki önceki ve sonraki id alabilirim??

3 Cevap

SELECT
   (SELECT id FROM YourTable WHERE id < YourId ORDER BY id DESC LIMIT 1) AS prev,
   (SELECT id FROM YourTable WHERE id > YourId ORDER BY id ASC LIMIT 1) AS next
;

Gerçek kimliği ile YourId değiştirin ve geçerli tablo adı ile YourTable değiştirin. Değerlerinden herhangi olacaksa NULL daha sonra verilen hiçbir Önceki / sonraki unsur vardır.

Eğer böyle bir şey denemek olabilir -

Sonraki için SEÇ id yourtable DAN id> '$ current_page_id' LIMIT 1

SEÇİN id yourtable DAN where id < Önceki için '$ current_page_id' LIMIT 1

Eğer @ RaYell başına cevap olarak bunu bir sorgu yapabilirsiniz.

SELECT MAX(id) FROM mytable WHERE id < 11
  • 11 ÖNCE kimliği almak için

    Id> 11 mytable MIN (id) SEÇİMİ

  • 11 SONRA kimliği almak için