MySQL timestamp select date range

后端 未结 7 1067
栀梦
栀梦 2021-02-01 14:32

Not sure really where to start with this one. Can anyone help/point me in the right direction.

I have a timestamp column in MySQL and I want to select a date range for e

相关标签:
7条回答
  • 2021-02-01 14:48

    A compact, flexible method for timestamps without fractional seconds would be:

    SELECT * FROM table_name 
    WHERE field_name 
    BETWEEN UNIX_TIMESTAMP('2010-10-01') AND UNIX_TIMESTAMP('2010-10-31 23:59:59')
    

    If you are using fractional seconds and a recent version of MySQL then you would be better to take the approach of using the >= and < operators as per Wouter's answer.

    Here is an example of temporal fields defined with fractional second precision (maximum precision in use):

    mysql> create table time_info (t_time time(6), t_datetime datetime(6), t_timestamp timestamp(6), t_short timestamp null);
    Query OK, 0 rows affected (0.02 sec)
    
    mysql> insert into time_info set t_time = curtime(6), t_datetime = now(6), t_short = t_datetime;
    Query OK, 1 row affected (0.01 sec)
    
    mysql> select * from time_info;
    +-----------------+----------------------------+----------------------------+---------------------+
    | 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34 |
    +-----------------+----------------------------+----------------------------+---------------------+
    1 row in set (0.00 sec)
    
    0 讨论(0)
  • 2021-02-01 14:51

    Usually it would be this:

    SELECT * 
      FROM yourtable
     WHERE yourtimetimefield>='2010-10-01'
       AND yourtimetimefield< '2010-11-01'
    

    But because you have a unix timestamps, you'll need something like this:

    SELECT * 
      FROM yourtable
     WHERE yourtimetimefield>=unix_timestamp('2010-10-01')
       AND yourtimetimefield< unix_timestamp('2010-11-01')
    
    0 讨论(0)
  • 2021-02-01 14:52

    This SQL query will extract the data for you. It is easy and fast.

    SELECT *
      FROM table_name
      WHERE extract( YEAR_MONTH from timestamp)="201010";
    
    0 讨论(0)
  • 2021-02-01 14:55

    I can see people giving lots of comments on this question. But I think, simple use of LIKE could be easier to get the data from the table.

    SELECT * FROM table WHERE COLUMN LIKE '2013-05-11%'
    

    Use LIKE and post data wild character search. Hopefully this will solve your problem.

    0 讨论(0)
  • 2021-02-01 14:55

    Whenever possible, avoid applying functions to a column in the where clause:

    SELECT *
      FROM table_name
     WHERE timestamp >= UNIX_TIMESTAMP('2010-10-01 00:00:00') 
       AND timestamp <  UNIX_TIMESTAMP('2010-11-01 00:00:00');
    

    Applying a function to the timestamp column (e.g., FROM_UNIXTIME(timestamp) = ...) makes indexing much harder.

    0 讨论(0)
  • 2021-02-01 14:58
    SELECT * FROM table WHERE col >= '2010-10-01' AND col <= '2010-10-31'
    
    0 讨论(0)
提交回复
热议问题