开发者

Get all 24 hours in a sql query

开发者 https://www.devze.com 2023-03-04 17:00 出处:网络
my question is how can I select all 24 hours in a day as data in a select? There is a more polished way to do that:

my question is how can I select all 24 hours in a day as data in a select?

There is a more polished way to do that:

select 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23
  from开发者_运维技巧 dual

My target db is Mysql, but a sql-standard solution is appreciated!


MySQL doesn't have recursive functionality, so you're left with using the NUMBERS table trick -

  1. Create a table that only holds incrementing numbers - easy to do using an auto_increment:

    DROP TABLE IF EXISTS `example`.`numbers`;
    CREATE TABLE  `example`.`numbers` (
      `id` int(10) unsigned NOT NULL auto_increment,
       PRIMARY KEY  (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    
  2. Populate the table using:

    INSERT INTO NUMBERS
      (id)
    VALUES
      (NULL)
    

    ...for as many values as you need. In this case, the INSERT statement needs to be run at least 25 times.

  3. Use DATE_ADD to construct a list of hours, increasing based on the NUMBERS.id value:

    SELECT x.dt
      FROM (SELECT TIME(DATE_ADD('2010-01-01', INTERVAL (n.id - 1) HOUR)) AS dt
              FROM numbers n
             WHERE DATE_ADD('2010-01-01', INTERVAL (n.id - 1) HOUR) <= '2010-01-02' ) x
    

Why Numbers, not Dates?

Simple - dates can be generated based on the number, like in the example I provided. It also means using a single table, vs say one per data type.


SELECT * from dual WHERE field BETWEEN 0 AND 24 
0

精彩评论

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