[英]Mysql get results for current month
我試圖每天從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
我的表格名稱是交易,包括日期,ID和貸方字段。 我嘗試了下面在網上找到的代碼,但只顯示了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'))
用SQL可以實現
建議您使用表“ your_table ”,其中包含“ value ”和“ date ”字段。 然后,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;
如您所要求的示例,例如(:)),您就這樣獲取了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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.