Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select the nearest value before and after

Tags:

sql

mysql

I have a table like this

let say the table is show_date

different | date
----------------------  
    -2    | 2011-04-18
----------------------
    -1    | 2011-04-19
----------------------
     4    | 2011-04-24
----------------------
     5    | 2011-04-25 
----------------------

I want to select 2 values, the first one is the first negative value and the second one is the first positive value. in this sample will result -1 (2011-04-19) and 4 (2011-04-24)

I've try order by abs(different) but it give the 2 nearest which is -1 and -2

like image 576
Yanuar Lutfi Avatar asked Feb 25 '23 12:02

Yanuar Lutfi


1 Answers

(SELECT * FROM show_date WHERE different < 0 ORDER BY different DESC LIMIT 1)
UNION ALL
(SELECT * FROM show_date WHERE different >= 0 ORDER BY different LIMIT 1)
like image 164
zerkms Avatar answered Mar 11 '23 16:03

zerkms