I imagine this is pretty simple, but can\'t figure it out. I\'m trying to make a few pages - one which will contain results selected from my mysql db\'s table for today, thi
To get last week's data in MySQL. This works for me even across the year boundries.
select * from orders_order where YEARWEEK(my_date_field)= YEARWEEK(DATE_SUB(CURRENT_DATE(), INTERVAL 1 WEEK));
To get current week's data
select * from orders_order where YEARWEEK(date_sold)= YEARWEEK(CURRENT_DATE());
Nathan's answer is very close however it will return a floating result set. As the time shifts, records will float off of and onto the result set. Using the DATE()
function on NOW()
will strip the time element from the date creating a static result set. Since the date()
function is applied to now()
instead of the actual date
column performance should be higher since applying a function such as date()
to a date column inhibits MySql's ability to use an index.
To keep the result set static use:
SELECT * FROM jokes WHERE date > DATE_SUB(DATE(NOW()), INTERVAL 1 DAY)
ORDER BY score DESC;
SELECT * FROM jokes WHERE date > DATE_SUB(DATE(NOW()), INTERVAL 1 WEEK)
ORDER BY score DESC;
SELECT * FROM jokes WHERE date > DATE_SUB(DATE(NOW()), INTERVAL 1 MONTH)
ORDER BY score DESC;
Everybody seems to refer to date being a column in the table.
I dont think this is good practice. The word date might just be a keyword in some coding language (maybe Oracle) so please change the columnname date to maybe JDate.
So will the following work better:
SELECT * FROM jokes WHERE JDate >= CURRENT_DATE() ORDER BY JScore DESC;
So we have a table called Jokes with columns JScore and JDate.
I think using NOW()
function is incorrect for getting time difference. Because by NOW()
function every time your are calculating the past 24 hours.
You must use CURDATE()
instead.
function your_function($time, $your_date) {
if ($time == 'today') {
$timeSQL = ' Date($your_date)= CURDATE()';
}
if ($time == 'week') {
$timeSQL = ' YEARWEEK($your_date)= YEARWEEK(CURDATE())';
}
if ($time == 'month') {
$timeSQL = ' Year($your_date)=Year(CURDATE()) AND Month(`your_date`)= Month(CURDATE())';
}
$Sql = "SELECT * FROM jokes WHERE ".$timeSQL
return $Result = $this->db->query($Sql)->result_array();
}
You can do same thing using single query
SELECT sum(if(DATE(dDate)=DATE(CURRENT_TIMESTAMP),earning,null)) astodays,
sum(if(YEARWEEK(dDate)=YEARWEEK(CURRENT_DATE),earning,null)) as weeks,
IF((MONTH(dDate) = MONTH(CURRENT_TIMESTAMP()) AND YEAR(dDate) = YEAR(CURRENT_TIMESTAMP())),sum(earning),0) AS months,
IF(YEAR(dDate) = YEAR(CURRENT_TIMESTAMP()),sum(earning),0) AS years,
sum(fAdminFinalEarning) as total_earning FROM `earning`
Hope this works.
Try using date and time functions (MONTH(), YEAR(), DAY(), MySQL Manual)
This week:
SELECT * FROM jokes WHERE WEEKOFYEAR(date)=WEEKOFYEAR(NOW());
Last week:
SELECT * FROM jokes WHERE WEEKOFYEAR(date)=WEEKOFYEAR(NOW())-1;