0

I have a requirement of getting next date and previous date

the table structure is as follows

| auto_id | id | next_date  | next_activity |
|    1    |  1 | 22-12-2012 |     -         |
|    2    |  1 | 25-12-2012 |     -         |
|    3    |  1 | 26-12-2012 |     -         |
|    4    |  1 | 28-12-2012 |     -         |

so i need next_day and previous_day next_day = next_date after current day previous_day = next_date before current_date

(SELECT * FROM `activity` WHERE id = 1 and next_date > CURDATE() order by next_date asc limit 1)
UNION
(SELECT * FROM `activity` WHERE id = 1 and next_date = CURDATE() )
UNION
(SELECT * FROM `activity` WHERE id = 1 and next_date < CURDATE() order by next_date desc limit 1)
ORDER BY next_date desc limit 2

Other way to do it self join the table...

Is there a way to optimize the table

1 Answer 1

1

Here is another way:

SELECT next_date, date_diff
 FROM (SELECT *,
               @dateDiff := datediff(next_date, curdate()) AS date_diff,
               @pDateDiff :=
                  IF((@dateDiff < 0 AND @dateDiff > @pDateDiff),
                     @dateDiff,
                     @pDateDiff)
                  AS pDateDiff,
               @nDateDiff :=
                  IF((@dateDiff > 0 AND @dateDiff < @nDateDiff),
                     @dateDiff,
                     @nDateDiff)
                  AS nDateDiff
          FROM activity, (SELECT @pDateDiff := -9999, @nDateDiff := 9999) tmp
          WHERE id = 1) aView
 WHERE date_diff IN (@pDateDiff, 0, @nDateDiff)
ORDER BY next_date;

date_diff value gives perspective of prev and next dates.

  • pick all dates where id = 1
  • find the date difference between next_date and curdate() & store in an user defined variable @dateDiff.
  • @pDateDiff is another variable which tracks maximum among negative @dateDiff values (our previous date)
  • @nDateDiff is yet another variable which tracks minimum among positive @dateDiff values (our next date)
  • in the end, select only those dates which are in (-ve max, 0, +ve min).

PS: if you've duplicate date entries then query may return all of them.

3
  • the problem would come when the difference is not 1 always... so if the previous date was 9 days ago and next dates are 1,2 days respectively, we do not get the boundaries right.
    – Masade
    Feb 26, 2013 at 13:56
  • @Masade Ok, check the updated query using Explain against union of three separate queries. Feb 26, 2013 at 14:33
  • can you please help me understand the query.
    – Masade
    Feb 26, 2013 at 18:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.