开发者

Selecting from a MySQL DB based on parts of a timestamp

Is there a way to select rows from a DB开发者_StackOverflow 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). Is there a way to do this? How else might I go about doing something like this? Thanks for your help!

-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.

Reference:

  • STR_TO_DATE


As simple as:

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


Use FROM_UNIXTIME similar to this:

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.

Alternatively you can also convert it to a 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. 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
  }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜