简体   繁体   中英

Best method for making a MySQL query dynamic (e.g., update query parameters to show Previous Week)

I have a query which calculates the total hours worked for the current week by task:

SELECT name AS 'Task Name'
       , sum(hours) AS `Total Hours`
        FROM time_records
        WHERE yearweek(record_date, 3) = yearweek(now(), 3)
        GROUP BY
        weekday(record_date), name

The WHERE clause specifies the current week:

WHERE yearweek(record_date, 3) = yearweek(now(), 3)

This data is displayed as a table using the MySQL query and a PDO statement.

I would now like to add an option for the viewer to see the previous week of data by clicking a link under the table (eg, "Previous Week"). In order to show that data, I would need to update the WHERE clause to query for the previous week:

   WHERE yearweek(record_date, 3) = yearweek(now(), 3) - 1

I'm wondering what the best way to do this is? I would prefer to keep just one version of the overall query. One thought is to use PHP to add the "- 1" to the query, such as:

WHERE yearweek(record_date, 3) = yearweek(now(), 3) <?php if (prev) {echo "- 1" ;} ?>

I think this should work, but how can I determine the prev condition? Should I make the entire query be inside a function so that for the default it can be "Time_hours(0)" and for the previous it can be "Time_hours(1)" - or is there some better way?

I'm concerned about keeping the code manageable and following best practices. Any tips would be appreciated. Thanks!

I suggest you try a query that has a parameter for the number of weeks ago you want to process. YEARWEEK is a bad choice for weekly processing because it handles end-of-year rollovers poorly.

Try this, if your weeks begin on Sunday. This will give the current week.

select r.record_id, r.record_date, w.week weekstart
from record r
join (
    select 
      (FROM_DAYS(TO_DAYS(CURDATE()) -MOD(TO_DAYS(CURDATE()) -1, 7)) 
           - interval 0 week) week
 )w
where record_date >= w.week
  and record_date < w.week + interval 1 week

Fiddle: http://sqlfiddle.com/#!2/4c487/1/0

If you want, let's say, one week ago, change - interval 0 week to - interval 1 week in your query. See this fiddle. http://sqlfiddle.com/#!2/4c487/2/0

You can put an an arbitrary number of weeks ago, even weeks that span year ends. See here for interval -42 week for example. http://sqlfiddle.com/#!2/4c487/3/0

The expression FROM_DAYS(TO_DAYS(CURDATE()) -MOD(TO_DAYS(CURDATE()) -1, 7)) rounds the current date down to the previous Sunday. If you want to round it to the previous Monday, use FROM_DAYS(TO_DAYS(CURDATE()) -MOD(TO_DAYS(CURDATE()) -2, 7)) . For example: http://sqlfiddle.com/#!2/4c487/8/0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM