1

I have a table with a value column. I need to select the line chosen by the user (on the front), one line above and one line below, so:

My 'orders' table rows

----------------------------------------------
id   |   price |
----------------------------------------------
1    |  1500.00 | 
2    |  1380.00 |
3    |  1880.00 |
4    |  1900.00 |
5    |  1450.00 |
6    |  1700.00 |

If the person chose: 1450.00, I want to bring 1450.00, 1380.00 and 1500.00. Is it possible to make this MySql select? or will i have to do this in php?

I only have the initial query for now:

SELECT * FROM `orders`
ORDER BY price;
Dharman
  • 30,962
  • 25
  • 85
  • 135

5 Answers5

1

You could select max and min price to get row. Let try this code:

SELECT * 
FROM orders A
WHERE A.price = 1450.00
OR A.price = (SELECT MAX(B.price) FROM orders B WHERE B.price < 1450.00)
OR A.price = (SELECT MIN(B.price) FROM orders B WHERE B.price > 1450.00)
Au Nguyen
  • 655
  • 4
  • 12
0

One way you could do it is using 2 MySQL statements. Something like:

SELECT * FROM `orders` WHERE `price`>=$user_price ORDER BY `price` ASC LIMIT 2

Which should give you the user's selected price and the row above. Then you can execute

SELECT * FROM `orders` WHERE `price`<$user_price ORDER BY `price` DESC LIMIT 1

Which should give you the row below.

I'm not sure if there's a way to combine the two queries, but if I do find anything I'll update the answer :)

ashiswin
  • 637
  • 5
  • 11
0

Here's how to get this, use max() on < 1450 and and min() on > 1450

select * from test
where price in 
    (select price from test where price = 1450)
        or price in
            (select max(price) from test where price < 1450)
            or price in
                (select min(price) from test where price > 1450)

instead of using or, use in instead to more cleaner.

select * from test
where price in (1450, 
   (select max(price) from test where price < 1450),           
         (select min(price) from test where price > 1450))

see dbfiddle

Ed Bangga
  • 12,879
  • 4
  • 16
  • 30
0

If the prices are unique and you want exactly three rows:

(select o.*
 from orders o
 where o.price <= :price
 order by o.price
 limit 2
) union all
(select o.*
 from orders o
 where o.price > :price
 order by o.price desc
 limit 1
);

Your question does not clarify what to do in these cases:

  • When the price is less than or equal to the minimum price.
  • When the price is greater than or equal to the maximum price.
  • When there are duplicate prices.
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

I think this query should work

select price 
    from orders
    where price <= (select min(price) from orders where price > 1450.00)
order by price desc
limit 3
momo
  • 141
  • 6