views:

893

answers:

1

Dear All

I have a MySQL db and inside it a table called ProductMaster with 6 fields "Product_Id,Product_Name,Model,Opening_date,Closing_Date,Status". Opening_Date and Closing Date Can accept null values.So some records has values for this field

I have the below query to display records from this table.

"select Product_Id,Product_Name,Model from ProductMaster  where Status=1"

Now I want to change the query to have a filter on the Opening_Date and Closing_Date if they are not null

Ex : If a Record is having Opening_Date as 05/01/2009 and Closing Date as 05/30/2009 Then i want to check whether today is a date in between these two dates and if Yes ,Returns the records

If both field values are empty, Return Records

Can any one help me to frame the query ? Thanks in advance

+2  A: 

The WHERE part of a query (the "WHERE clause") is just a long boolean expression. What does this mean? That MySQL just wants it to return either true or false, which it understands as "Yes. Include this row in the results." or "No. Don't include this row in the results."

If I understand correctly, you want to do two things:

  1. Check if the opening_date and closing_date are null
  2. Check if today is between those two dates.

And you want #2 to only happen if #1 is true. Which could be expressed like:

#1 AND #2

Which would be evaluated as false if either #1 or #2 is false.

That can be translated as:

  1. (opening_date IS NOT NULL) AND (closing_date IS NOT NULL)
  2. NOW() >= opening_date AND NOW <= closing_date

So if we treat those two like the #1 and #2 in the expression we said we were going to use (#1 AND #2) then we get:

((opening_date IS NOT NULL) AND (closing_date IS NOT NULL)) 
AND (NOW() >= opening_date AND NOW <= closing_date`)

And that's the WHERE clause you need.

scraimer