简体   繁体   English

根据时间戳的一部分从MySQL数据库中选择

[英]Selecting from a MySQL DB based on parts of a timestamp

Is there a way to select rows from a DB where the timestamp is in a certain year? 有没有一种方法可以从某个年份的时间戳记中的数据库中选择行? I don't have a specific timestamp, just a range (ex. all timestamps within the year 2009). 我没有具体的时间戳,只是一个范围(例如2009年内的所有时间戳)。 Is there a way to do this? 有没有办法做到这一点? How else might I go about doing something like this? 我还能怎么做这样的事情? Thanks for your help! 谢谢你的帮助!

-iMaster -iMaster

Use: 采用:

WHERE timestamp_col BETWEEN STR_TO_DATE('2009-01-01', '%Y-%m-%d') 
                        AND STR_TO_DATE('2009-12-31', '%Y-%m-%d')

Any functions performed on a column mean that an index, if one exists for that column, can not be used. 在列上执行的任何功能都意味着无法使用索引(如果该列存在索引)。

I used the STR_TO_DATE function to ensure that whatever date provided as a string could be interpreted by MySQL as a TIMESTAMP. 我使用STR_TO_DATE函数来确保MySQL提供的任何字符串形式的日期都可以解释为TIMESTAMP。

Reference: 参考:

Use FROM_UNIXTIME similar to this: 使用类似于此的FROM_UNIXTIME

SELECT
  FROM_UNIXTIME(my_timestamp, '%Y') AS year
FROM
  table_name
WHERE
  FROM_UNIXTIME(my_timestamp, '%Y') = 2009;

Where 'my_timestamp' is the name of your timestamp column. 其中“ my_timestamp”是您的时间戳列的名称。

Alternatively you can also convert it to a DATETIME 另外,您也可以将其转换为DATETIME

If you convert it to datetime you can do it by using the mysql DATE_FORMAT function which allows you to take a DATETIME and format it as a date. 如果将其转换为日期时间,则可以使用mysql DATE_FORMAT函数来实现,该函数允许您获取DATETIME并将其格式化为日期。 Then group by that column. 然后按该列分组。

  private function _formatDate() {
    if ($this->_granularity == 'month') {
      return '%y/%M';
    }elseif($this->_granularity == 'day') {
      return '%y/%M/%d';
    }
  } 

  public function getmyquery() {
    $query = "
 SELECT count( * ) as visits, DATE_FORMAT( `myOriginalDateField` , '".$this->_formatDate()."' ) AS mydate
 FROM `mys`
 WHERE id = ".$this->_Id."
 GROUP BY mydate
 ORDER BY mydate ASC
 ";
    return $query
  }

简单如:

SELECT * FROM table WHERE YEAR(timestamp) = '1999'

An important addition to the excellent suggestions already given here: if you plan on executing this query as a part of rendering your pages (as opposed to running this as a one-off report), you should really consider performance. 这里已经给出的出色建议的重要补充:如果计划在呈现页面的过程中执行此查询(而不是将其作为一次性报告运行),则应真正考虑性能。 Indexes won't help you much if you're post-processing the column value with a function before comparing it to something. 如果您要先使用函数对列值进行后处理,然后再与其他对象进行比较,则索引将无济于事。

In that case, I would consider creating a separate database column that contains JUST the year, or just the month, etc. 在这种情况下,我会考虑创建一个单独的数据库列,其中仅包含年份,或者仅包含月份等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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