I
I
Igor Bezlepkin2017-08-23 17:10:50
MySQL
Igor Bezlepkin, 2017-08-23 17:10:50

How to build an SQL query to display one result from past dates, and several from future ones?

Hey! There is a table, in it material ID and TIMESTAMP. You need to make a query like this: find the first nearest date from past dates, and all the rest from future ones.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2017-08-23
@0xD34F

SELECT `date`
FROM `foo`
WHERE `id` >= (
  SELECT `id`
  FROM `foo`
  WHERE `date` < now()
  ORDER BY `id` DESC
  LIMIT 1
)

This is of course assuming the dates are consecutive. If not, then you can, for example, separately select the last past one and separately all future ones and combine them with a union.

R
Rsa97, 2017-08-23
@Rsa97

SELECT ...
  FROM `table` 
  WHERE `date` < NOW()
  ORDER BY `date` DESC
  LIMIT 1
UNION SELECT ...
  FROM `table` 
  WHERE `date` >= NOW()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question