【问题标题】:MySQL compare by weekMySQL 按周比较
【发布时间】:2014-05-20 12:39:11
【问题描述】:

我有一个 select 语句,它需要将其 WHERE 基于时间戳,但对于从星期一开始的那一周内的所有日期。

MySQL

SELECT DISTINCT(unique_reference) AS unique_reference,  date(datetime) AS datetime
    FROM sales_tickets

    WHERE Date(datetime)='$datetime'

这是基于 $datetime 可以是任何日期,但 select 语句需要获取该周的所有记录,例如:如果是 2014 年 5 月 12 日星期一,它将获取该周的所有结果,而不是的一天。

目前,它只获取一天的结果。

我不知道如何纠正这个问题。任何建议都会非常感谢。

【问题讨论】:

  • DISTINCT 不是一个接受单个参数的函数。它适用于整行。

标签: mysql select


【解决方案1】:

您可以使用WEEK 函数进行比较:

WHERE WEEK(DATE(datetime)) = WEEK('$datetime')

如果您有多个年份的条目,您可以改用YEARWEEK function

编辑一周的第一天: WEEKYEARWEEK 函数都有第二个可选参数,用于告知一周的开始时间。尝试考虑模式 1 或 5。

Mode    First day of week   Range   Week 1 is the first week …
0   Sunday  0-53    with a Sunday in this year
1   Monday  0-53    with 4 or more days this year
2   Sunday  1-53    with a Sunday in this year
3   Monday  1-53    with 4 or more days this year
4   Sunday  0-53    with 4 or more days this year
5   Monday  0-53    with a Monday in this year
6   Sunday  1-53    with 4 or more days this year
7   Monday  1-53    with a Monday in this year

【讨论】:

  • 我能否发出警告,指出这将无法使用索引来搜索列,如果可能,最好使用 between 语句。
  • OP 希望每周从星期一开始,因此请注意选择适当的 modedefault 通常以星期日为基础)。
  • 没有。这不是 OP 的预期答案。
  • 这已经接近我的需要了,但是我如何从周一而不是周日开始这项工作呢?
  • 我刚刚编辑了答案以添加一周第一天的信息。
【解决方案2】:

一个 sargable 解决方案将明确计算您所需范围的起点和终点:

WHERE datetime >= DATE('$datetime') + INTERVAL 0 - WEEKDAY('$datetime') DAY
  AND datetime <  DATE('$datetime') + INTERVAL 7 - WEEKDAY('$datetime') DAY

【讨论】:

    【解决方案3】:

    最简单的方法可能是让您的 WHERE 语句检查一系列值,您可以预先计算这些值。 我假设您使用的是 php。

    所以你的 SQL 语句将是:

    SELECT DISTINCT(unique_reference) AS unique_reference,  date(datetime) AS datetime
    FROM sales_tickets
    
    WHERE (Date(datetime) > '$startDate')
       AND (Date(datetime) < '$endDate');
    

    您首先必须弄清楚 $startDate 和 $endDate 是什么:

    $endDate = strtotime('Monday', time()); // might need to adjust this depending on when your week starts 
    $startDate = $endDate - 7*24*60*60; //one week before.
    

    在 SQL 中使用的 unix 时间戳和日期时间之间转换时间时要小心,但你明白了。

    【讨论】:

      【解决方案4】:

      试试 WEEK():

      WHERE WEEK(datetime)=WEEK('$datetime')
      

      阅读更多:WEEK()

      【讨论】:

        猜你喜欢
        • 2023-04-03
        • 2021-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-13
        • 1970-01-01
        • 1970-01-01
        • 2023-03-17
        相关资源
        最近更新 更多