Skip to content
Advertisement

Filtering SQL results by date

Here is my query for a maintenance dates list.

SELECT `checkdates`.`checkdateplanneddate`, `checkdates`.`checkdatevehicle`, `checktypes`.`checktype`, `checktypes`.`emailto`, `checktypes`.`daysnotice`
FROM `checkdates`
    , `checktypes`
WHERE `checktypes`.`checktype` = `checkdates`.`checkdatechecktype`;

The idea is.. Everyday the server will email customers to let them know which checkdates are coming, based on the days notice that is set for that type of check. (see image)

Currently it is showing all checkdates.

All i need to do is filter the list so it only shows the dates that are “Todays date plus checktypes.daysnotice”

I have tried many different queries, but cannot seem to get the right combo.

Thank you in advance

I have attached an image to show that the data is available

The data is available, but I need to filter the dates

Advertisement

Answer

If I understand your question correctly, and assuming that you are running MySQL (as the use of backticks for quoting and the phpmyadmin screen copy indicate), you can use date arithmetics as follows:

SELECT cd.checkdateplanneddate, cd.checkdatevehicle, ct.checktype, ct.emailto, ct.daysnotice 
FROM checkdates cd
INNER JOIN checktypes ct ON ct.checktype = cd.checkdatechecktype
WHERE cd.checkdateplanneddate = current_date + interval ct.daysnotice day

The where condition implements the desired logic.

Side notes:

  • Use standard, explicit joins! Implicit joins (with commas in the from clause) is a very old syntax, that should not be used in new code

  • Table aliases make the query easier to write and read

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