简体   繁体   English

MySQL / PHP GROUP BY日

[英]MySQL/PHP GROUP BY day

I have query that groups all records by day. 我有查询按天分组所有记录。

$query = mysql_query("SELECT DATE_FORMAT(date, '%d/%m/%Y') AS day, COUNT(id) AS total FROM invoices GROUP BY day");

How i do that it shows me all days, even if there is no records, until today 我是怎么做到的,它向我展示了所有的日子,即使没有记录,直到今天

Omerimuni Omerimuni

I think it is best to just get all the records in the table, ordered by date and fill in the gaps using PHP. 我认为最好只获取表中的所有记录,按日期排序并使用PHP填补空白。

It is difficult to generate a sequence of dates in MySQL. 在MySQL中很难生成一系列日期。 You often see solutions with stored procedures and temp tables, like here . 您经常会看到包含存储过程和临时表的解决方案,例如此处

In PHP, create a loop that goes through each date until today. 在PHP中,创建一个循环,贯穿每个日期直到今天。 In the loop you can check for each record if a date exists in the results of the query. 在循环中,如果查询结果中存在日期,则可以检查每条记录。 If not, you can just render an empty row or whatever you want. 如果没有,您可以只渲染一个空行或任何你想要的。

This check is not so expensive, because you sort the results in the query by date as well, so you will only need to check if the current record has the same date as the current date in the loop. 此检查不是那么昂贵,因为您也按日期对查询中的结果进行排序,因此您只需要检查当前记录是否与循环中的当前日期具有相同的日期。 If the date of the record is greater, you should not process this record yet. 如果记录的日期更长,则不应处理此记录。 If the date is the same, process the record and fetch the next record. 如果日期相同,则处理记录并获取下一条记录。

Maybe this is not best solution, but i did it myself :D 也许这不是最佳解决方案,但我自己做了:D

$result = mysql_query("SELECT date_format(date, '%Y-%m-%d') AS date FROM invoices ORDER BY id ASC LIMIT 1");
    $first = mysql_fetch_array($result);

    $year = date('Y', strtotime($first['date']));
    $month = date('m', strtotime($first['date']));
    $day =  date('d', strtotime($first['date']));


    for ($i = strtotime($year.'-'.$month.'-'.$day); $i < strtotime('NOW'); $i=$i+24*60*60){
        $r = date('d/m/Y',$i);
        $res = mysql_query("SELECT DATE_FORMAT(date, '%d/%m/%Y') AS day, COUNT(id) AS total FROM invoices WHERE DATE_FORMAT(date, '%d/%m/%Y') LIKE '%$r%' GROUP BY day");
        $arr = mysql_fetch_array($res);

        if(mysql_num_rows($res)){
            echo "".$arr['day']."&nbsp;=>&nbsp;".$arr['total']."<br>";
        }else{
            echo date('d/m/Y',$i)."=>&nbsp; 0<br>";
        }
    }

There is no way to do this, unless you will have table with days. 没有办法做到这一点,除非你有几天的表。 Than you can left join on it 比你可以加入吧

In principle you could create a new table containing all days. 原则上,您可以创建一个包含所有日期的新表。 Then you left join this table into "invoices" on days. 然后你就把这张桌子加入了“发票”。

However, my suggestion for you is to instead handle this logic in PHP. 但是,我的建议是在PHP中处理这个逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM