【问题标题】:MySQL: Month Range JoinMySQL:月份范围连接
【发布时间】:2013-07-08 09:13:10
【问题描述】:

我有两张桌子:

**users**
id  firstname   lastname    
1   John        Mathews
2   Scott       Mithchell
....
....
....


**publish**
id  userid      bookid      published
1   1       1       2013-01-16 14:12:10
1   2       1       2013-01-08 15:17:40
1   2       1       2013-01-10 14:18:10
....
....
....

我需要根据字段“已发布”查找每个用户每个月(一月、二月、三月...等)的记录。如果相关月份没有该用户的数据,则应显示 0(零)。所以输出应该是这样的:-

id  firstname   lastname    month       published
1   John        Mathews     January     1
1   John        Mathews     february    2
1   John        Mathews     march       1
1   John        Mathews     april       1
1   John        Mathews     may         1
1   John        Mathews     june        1
1   John        Mathews     july        0
1   John        Mathews     august      0
1   John        Mathews     september   0
1   John        Mathews     October     0
1   John        Mathews     November    0
1   John        Mathews     December    1
2   Scott       Mitchell    January     2
2   Scott       Mitchell    february    2
2   Scott       Mitchell    march       1
2   Scott       Mitchell    april       1
2   Scott       Mitchell    may         1
2   Scott       Mitchell    june        0
2   Scott       Mitchell    july        0
2   Scott       Mitchell    august      1
2   Scott       Mitchell    september   1
2   Scott       Mitchell    October     0
2   Scott       Mitchell    November    0
2   Scott       Mitchell    December    1

【问题讨论】:

    标签: mysql join range


    【解决方案1】:

    ** 月 **

    nr | monthName
    ----------
    1  | january
    2  | february
    ...
    

    然后:

    SELECT p.id, fristname, lastname, m.monthName AS month, count(*) as published
    FROM months m LEFT JOIN publish p ON MONTH(p.published) = m.nr
    JOIN users u ON u.id = p.userid
    GROUP BY p.id, firstname, lastname, month
    ORDER BY ...
    

    【讨论】:

    • 我还需要在同一个查询中包含空月份。
    • 我们可以在运行时创建 Months 范围而不是创建单独的表吗?
    • 您可以对表格进行透视,有 12 个月的列,以及每个用户每年的计数器。这样可以吗?
    • 阅读 MySQL 的表旋转,现在应该很容易了:artfulsoftware.com/infotree/qrytip.php?id=78
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 2022-12-07
    • 2013-04-16
    • 2013-05-21
    相关资源
    最近更新 更多