【问题标题】:How to count how many rows contain a specific value如何计算有多少行包含特定值
【发布时间】:2015-02-11 13:52:23
【问题描述】:

我正在尝试计算每月有多少“返回”的值为“1”。这是我到目前为止所得到的:

$data1y=array();
$data2y=array();

$months_sql = array();


for ($i = 1; $i <= 12; $i++) {
    $months_sql[] = date("F", strtotime( date( 'Y-m-01' )." -$i months"));
}


    $sql = "SELECT returned, MONTHNAME( date_in) AS date_in
        FROM item
        WHERE  date_in >= NOW() - INTERVAL 1 YEAR";

    $query = mysql_query($sql);


    foreach($months_sql as $month)
    {
        while ($row = mysql_fetch_array($query))
        {
            if($row['date_in'] = $month && $row['returned']=='1')
            {
                $counter_returned++;
            }
            $counter_total++;
        }
        $data1y[] = $counter_returned++;
        $data2y[] = $counter_total++;;
    }

我想要的是在两个数组中存储每月总共有多少条记录,其中有多少条每月包含 1 条记录。

【问题讨论】:

  • 为什么不直接使用 MySQL 的 COUNT() 聚合函数呢?
  • 因为我想在当月没有数据的情况下显示0,而我用mysql做不到
  • 所以您只需要处理 COUNT 聚合函数的可能 null 即可。 If 语句就可以解决问题

标签: php mysql jpgraph


【解决方案1】:

你的循环有问题。您只会检查您的months_sql 数组中的第一个月(我认为是11 月?)。下个月,您将不再需要获取任何 db 结果。

您需要切换它们,如果这样做,您的计数器需要确定它们属于哪个月份,因为您的数据库数据不会每月得到处理:

while ($row = mysql_fetch_array($query))
{
    foreach($months_sql as $month)
    {
        if($row['date_in'] == $month)
        {
            if($row['returned']=='1')
            {
                $data1y[$month]++;
            }
            $data2y[$month]++;
        }
    }
}

使用 count() 的一种更快的方法

$sql = "SELECT MONTHNAME( date_in) AS date_in, returned, count(*) as count
    FROM item
    WHERE  date_in >= NOW() - INTERVAL 1 YEAR
    GROUP BY date_in, returned;";
$query = mysql_query($sql);

while ($row = mysql_fetch_array($query))
{
    if(in_array($row['date_in'], $months_sql))
    {
        if($row['returned']=='1')
        {
            $data1y[$month] = $row['count'];
        }
        $data2y[$month] += $row['count'];
    }
}

在任何一种情况下,如果您希望每个月使用 0 初始化数据,请在您的 db 查询之前添加:

foreach($months_sql as $month){
    $data1y[$month]=0;
    $data2y[$month]=0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 2012-04-17
    相关资源
    最近更新 更多