Mysql获取当月的结果

时间:2017-09-07 14:05:25

标签: php mysql database

我试图将mysql的结果导入每天1个月的PHP结果,如果行不存在则显示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

我的表名是交易,包括日期,ID和信用字段。我尝试了下面在网上找到的代码,但只显示了一行,我试图在两个日期的第一和第二十二个检索。

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'))

2 个答案:

答案 0 :(得分:2)

可以通过SQL实现

我们建议你有桌子&#34; your_table &#34;字段&#34; &#34;和&#34; 约会&#34;。然后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;

答案 1 :(得分:1)

例如你提出的示例(:))你像这样

获取了SQL
SELECT `date`, `credits` FROM `table_name` WHERE 1

获得一个名为 $ results 的数组,就像这样

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

因此,使用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);