【问题标题】:Showing data from a mysql table grouped by the month显示按月份分组的 mysql 表中的数据
【发布时间】:2011-09-10 12:02:57
【问题描述】:

基本上我在一个表中有很多数据及其创建日期。我想显示表格中的所有数据,但是在其输出中它需要按日期顺序排列,然后在其上方创建月份的标题。

一月 数据1 数据2 数据3

二月 数据4 数据5

三月 数据6 数据7 数据8 数据9

这可能来自一个查询吗?我正在使用 php 和 mysql。

谢谢

表格布局类似于:

ID | Type | Content | User | Colour | Creation Date

目前这都是理论,但我将在今天晚些时候和明天创建它。我只是想知道这是否可能。

【问题讨论】:

  • 什么是表格布局?
  • 是的,但它有助于查看您的表定义。你能相应地编辑你的问题吗?

标签: php mysql select


【解决方案1】:

我只需将月份添加到查询中,按日期对查询进行排序,然后在输出阶段跟踪月份并在每次月份更改时插入一个新标题:

SELECT *, MONTH(thedate) AS month FROM thetable ORDER BY thedate;

在 PHP 中:

$lastmonth = "";
while ($row = mysql_fetch_assoc($queryresult))
{
  if (empty($lastmonth)) { $lastmonth = $row['month']; }

  if ($lastmonth != $row['month'])
  {
    $lastmonth = $row['month'];
    // print new month header
  }

  // print row
}

【讨论】:

    【解决方案2】:
    $res = mysql_query( 'SELECT MONTHNAME(creation_date) AS month_name, data_name
                         FROM my_table ORDER BY creation_date' );
    $currentMonth = null;
    while( $row = mysql_fetch_assoc($res) ) {
        if( $currentMonth !== $row['month_name'] ) {
            echo '<h1>'.$row['month_name'].'</h1>';
            $currentMonth = $row['month_name'];
        }
        echo '<p>'.$row['data_name'].'</p>';
    }
    

    【讨论】:

      【解决方案3】:

      将 MONTH 列添加到您的架构并从创建日期开始填充它。您需要两列来执行此操作。

      这听起来更像是一个报告功能,而不是交易功能。如果您将 OLAP 数据库中的历史记录卸载到具有时间维度的报告星型模式中,则该解决方案将很容易。它也会减少您的 OLAP 数据集的大小。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-05
        • 2021-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-20
        相关资源
        最近更新 更多