0

I'm doing the following query and getting all rows returned, regardless of date:

 SELECT DISTINCT p.name, p.category, u.f_name, t.name
 FROM   (
        prizes p, tags t, results r
        )
 LEFT JOIN
        users u
 ON     (r.user_id = u.id)
 LEFT JOIN
        f_tag_lookup tl
 ON     (tl.tag_id = t.id)
 WHERE  r.tag_id = t.id
        AND r.date BETWEEN concat(date_format(LAST_DAY(now() - interval 1 month), '%Y-%m-'),'01') AND last_day(NOW() - INTERVAL 1 MONTH)

r.date is a datetime field. there are three rows with dates from last month and three rows with dates from this month but I'm getting all rows back?

Would appreciate any pointers. I want to return results between the first and last day of last month i.e. all results for July.

thanks,

2 Answers 2

3

Could you not just use the month() date function ?

e.g. use month(date) = month(now()) as the filter.

You would need to also match on year(date) = year(now()), if you had data from more than one year.

I'm not sure of the performance, but it seems more readable to me to express it that way.

SELECT DISTINCT p.name, p.category, u.f_name, t.name
FROM (prizes p, tags t, results r)
LEFT JOIN users u ON (r.user_id = u.id)
LEFT JOIN f_tag_lookup tl ON (tl.tag_id = t.id)
WHERE r.tag_id = t.id AND 
      month(r.date) = month(now()) AND 
      year(r.date) = year(now()) 
Sign up to request clarification or add additional context in comments.

3 Comments

MONTH(r.date) = 07 and Year(r.date) = 2009 can't be worse in performance than r.date BETWEEN concat(date_format(LAST_DAY(now() -interval 1 month),'%Y-%m-'),'01') AND last_day(NOW() - INTERVAL 1 MONTH)
perhaps not, but the use between operator, against a constant uper bound might be more optimal for indexed selection
thanks for the answers. So I would do month(now() - interval 1 month) for the previous month?
0

figured it out. The SQL regarding dates was fine but the JOINS were wrong. Thanks for the replies.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.