› MySQL 5.5 Community Server
› MySQL 5.6 Community Server
› Percona Configuration Wizard
› XtraBackup 搭建主从复制
Great Sites on MySQL
› Percona
› MySQL Performance Blog
› Severalnines
推荐管理工具
› Sequel Pro
› phpMyAdmin
推荐书目
› MySQL Cookbook
MySQL 相关项目
› MariaDB
› Drizzle
参考文档
› http://mysql-python.sourceforge.net/MySQLdb.html
AntiGameZ
V2EX  ›  MySQL

求助一个MySQL的查询,折腾了2个多小时了……

  •  
  •   AntiGameZ · Jun 1, 2011 · 6516 views
    This topic created in 5598 days ago, the information mentioned may be changed or developed.
    基本查询是这样的:
    SELECT DATE_FORMAT(CreateTime, '%Y-%m-%d %H:00:00') t, count(*) c
    FROM Table1
    group by t
    生成的结果是:
    t c
    2010-03-12 13:00:00 2
    2010-03-15 10:00:00 1
    2010-03-17 08:00:00 1
    2010-03-18 09:00:00 1

    因为出来的结果时间上不连续,所以我自己又造了一个时间表(最小单位是小时),对时间表的基本查询是这样:

    SELECT dt
    FROM Calendar
    dt
    1970-02-06 03:00:00
    1970-02-06 04:00:00
    1970-02-06 05:00:00
    1970-02-06 06:00:00
    1970-02-06 07:00:00
    ……
    一直延续到2020年

    不知道应该怎么写查询,才能生成如下的结果:
    2010-03-12 13:00:00 2
    2010-03-12 14:00:00 0
    2010-03-12 15:00:00 0
    ……

    即时间在小时上连续,如果此时间内没有记录,就取0

    不知道自己描述的清楚不清楚。
    7 replies  •  1970-01-01 08:00:00 +08:00
    kerie
        1
    kerie  
       Jun 1, 2011
    我也遇到类似的问题,求会的人解答一下
    napoleonu
        2
    napoleonu  
       Jun 1, 2011
    select c.dt,ifnull(tmp1.format_t,0)

    from

    (select date_format(t1.CreateTime, '%Y-%m-%d %H:00:00') format_t, count(*) count_c from Table1 t1 group by t1.t) tmp1

    right join Calendar c

    on tmp1.format_t=c.dt;
    billychow
        3
    billychow  
       Jun 1, 2011
    难道一定要用 MySQL?就为了生成一个连续的时间还得再去造个 Calendar 表?

    如果你一定要纠结于这种方式实现的话,那么子查询再联接表应该可以搞定。

    PS: 好久木写过 SQL 了,连语法都忘得差不多了
    napoleonu
        4
    napoleonu  
       Jun 1, 2011
    group by t1.format_t

    不好意思。。
    raptium
        5
    raptium  
       Jun 1, 2011
    这是考 outer join 对吧= =
    AntiGameZ
        6
    AntiGameZ  
    OP
       Jun 1, 2011
    @billychow 我只想得到这个办法,如果有高明的办法请教教我。因为我是做统计,得到结果以后倒入到另外一个系统里,所以不想再写个程序了。
    @raptium 是,不过搞不懂的倒是Outer Join本身,而是MySQL本身一些诡异的地方,说诡异是因为照着自己的思路在SQL Server上都跑的动,一换MySQL就不行了。
    AntiGameZ
        7
    AntiGameZ  
    OP
       Jun 1, 2011
    @napoleonu 谢谢谢谢,问题终于解决
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2833 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 14:37 · PVG 22:37 · LAX 07:37 · JFK 10:37
    ♥ Do have faith in what you're doing.