Skip to content
Advertisement

MySQL get the nearest future date to given date, from the dates located in different table having Common ID

I have two tables – Client and Banquet

The result to be generated is such that

1. The Date which is FUTURE : CLOSEST or EQUAL to the current date, which is further related to the respective client should be filtered and ordered in format given in Required Result

CURDATE() for current case is 5.2.2016

FAILED: Query Logic 1

FAILED: Query Logic 2

sqlfiddle

UPDATE : Further result to be generated is such that

2. Clients WITHOUT : DATED should also be listed : may be with a NULL

3. the information other then DATED in the BANQUET table also need to be listed

UPDATED Required Result

Advertisement

Answer

For this query, I suggest applying your WHERE condition >= CURDATE() and then SELECT the MIN(dated) with GROUP BY client_id:

From this, you can add the necessary JOIN to the client table to get the client name:

SQLFiddle: http://sqlfiddle.com/#!9/aded8/18

EDITED TO REFLECT NEW PARTS OF QUESTION:

Based on the new info you added – asking how to handle nulls and the ‘meal’ column, I’ve made some changes. This updated query handles possible null values (by adjusting the WHERE clause) in dated, and also includes meal information.

or you can take some of this and combine it with Gordon Linoff’s answer, which sounds like it will perform better overall.

New SQLFiddle: http://sqlfiddle.com/#!9/a4055/2

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement