is there a simpler way than writing:
select date_sub(curdate(), interval WEEKDAY(curdate()) day) as LastMonday
from dual
In MySQL, you can subtract any date interval using the DATE_SUB() function. Here, since you need to subtract one day, you use DATE_SUB(CURDATE(), INTERVAL 1 DAY) to get yesterday's date.
You can use DATE() from MySQL to select records with a particular date. The syntax is as follows. SELECT *from yourTableName WHERE DATE(yourDateColumnName)='anyDate'; To understand the above syntax, let us first create a table.
MySQL WEEKDAY() FunctionThe WEEKDAY() function returns the weekday number for a given date. Note: 0 = Monday, 1 = Tuesday, 2 = Wednesday, 3 = Thursday, 4 = Friday, 5 = Saturday, 6 = Sunday.
If you're not using an ancient MySQL, you can wrap this in a stored function.
CREATE FUNCTION `LastMonday`() RETURNS DATETIME
RETURN DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY) ;
and then call
select LastMonday() as LastMonday
Update:
If you're having performance problems, you can persist the value in a session variable. That way you can be sure that it will only be calculated once.
set @LastMonday=LastMonday();
select @Lastmonday;
(in this simple query it makes no difference of course...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With