简体   繁体   English

MySQL获取当前月份的结果

[英]Mysql get results for current month

I am trying to get results from mysql into php results for 1 month with each day, and if row doesn't exist then display 0 to that date like below 我试图每天从mysql的结果转换成php结果1个月,如果行不存在,则显示0到该日期,如下所示

2017-09-07 - 70
2017-09-10 - 0
2017-09-11 - 100
2017-09-12 - 0
2017-09-15 - 0
2017-09-20 - 0
2017-09-29 - 200

My table name is transactions and includes date, id, and credits fields. 我的表格名称是交易,包括日期,ID和贷方字段。 I tried below code I found online, but only shows 1 row, where I was trying two retrieve for two dates 1st and 26th for testing. 我尝试了下面在网上找到的代码,但只显示了1行,在这里我尝试两次检索两个日期1st和26th进行测试。

SELECT MonthDate.Date, COALESCE(SUM(`credits`), 0) FROM ( SELECT 1 AS Date UNION ALL SELECT 26) AS MonthDate LEFT JOIN transactions AS T1 ON MonthDate.Date = DAY(T1.Date) AND MONTH(T1.Date) = 9 AND YEAR(T1.Date) = 2017 WHERE MonthDate.Date <= DAY(LAST_DAY('2017-09-28'))

It is possible to achieve with SQL 用SQL可以实现

Let's suggest that you have table " your_table " with fields " value " and " date ". 建议您使用表“ your_table ”,其中包含“ value ”和“ date ”字段。 Then SQL will look like: 然后,SQL将如下所示:

select a.Date, IFNULL(your_table.value, 0)
from (
  select curdate() + INTERVAL 31 DAY - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as Date
  from (
    select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9
    ) as a
  cross join (
    select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9
    ) as b
  cross join (
    select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9
    ) as c
  ) a
left join your_table on your_table.date = a.Date
where a.Date between 'PUT_START_DATE_HERE' and 'PUT_END_DATE_HERE'
order by a.Date;

Example as you asked, for example ( :) ) you fetched your SQL like this 如您所要求的示例,例如(:)),您就这样获取了SQL

SELECT `date`, `credits` FROM `table_name` WHERE 1

And get an array called $results like this 并获得一个名为$ results的数组,像这样

2017-09-07 => 70
2017-09-11 => 100
2017-09-29 => 200

So with php help, you can fill empty days like this 因此,借助php帮助,您可以像这样填补空缺的日子

$date = (new DateTime());
$lastDay = $date->modify('last day of this month')->format('d');
$firstDay = $date->modify('first day of this month')->format('d');

for($day = 0; $day < $lastDay; $day++) {
    $date = (new DateTime())
        ->modify('first day of this month')
        ->modify('+' . $day . ' day')
        ->format('Y-m-d');

    if(empty($result[$date])) {
        $result[$date] = 0;
    }
}

var_dump($result);

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

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