Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Return previous days entries

Status
Not open for further replies.

kzn

MIS
Jan 28, 2005
209
GB
Hi

I have been trying to run a query to return all the previous days entries. I cant use interval - 1 day because lets say the last entry was on friday and I am running the query on monday, it would return 0 results.

This is the select statement I have so far:
select * from timesheet where date(dateTimeStamp) = date(now()) order by dateTimeStamp desc;

I am out of ideas how to manipulate it. Any ideas appreciated.

Many thanks
 
Hi, I think I have found the answer on the mysql site, thought I would post it here just in case someone else needs it.

In most cases you need results from yesterday, but for Sunday and Monday we
must correct extra for the weekend.

DAYOFWEEK() returns 1 for Sunday, 2 for Monday, etc., so we can use this to
make a correction value:

SET @COR = (DAYOFWEEK(NOW()) < 3) * DAYOFWEEK(NOW());
SELECT * FROM table WHERE `datetime` > CURDATE() - INTERVAL (1 + @COR) DAY
AND `datetime` < CURDATE() - INTERVAL @COR DAY;

This construction is index-friendly, because MySQL will reduce the
calculation to a constant before running the query. The result is a simple
col > constant expression which can make use of indexes if they are present.
Expressions such as TO_DAYS(`datetime`) (as suggested by you) will result in
a full table scan and slow down the query significantly.

If you consider Saturday as a business day you only need to make a
correction for Monday:

SET @COR = (DAYOFWEEK(NOW()) = 2);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top