在日期之间循环并显示每个日期的记录

时间:2014-07-04 09:39:12

标签: php mysql sql database

select * from myTable where dates between "xxxx-xx-xx" and "yyyy-yy-yy" 

我希望每个日期都有这个表的结果。当myTable不包含该日期的记录时,该日期的每个字段都将为空。

2 个答案:

答案 0 :(得分:1)

这需要动态日期生成以及我之前的回答MySQL show count of 0 for dates with no records

以下是您可以做的事情

select 
t1.dates as dates,
t2.id
from
(
  select a.Date as dates 
  from (
    select curdate() - 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
  where a.Date BETWEEN '2014-01-01' AND '2014-01-10'
)t1
left join
(
  select * from myTable
)t2
on t2.dates = t1.dates

<强> DEMO

答案 1 :(得分:0)

$from = '2014-07-01';
$to = '2014-07-06';
$empty_row = array(
    'text' => null
);

$from_timestamp = strtotime($from . ' midnight');
$to_timestamp = strtotime($to . ' midnight');

$dates = range($from_timestamp, $to_timestamp, 86400);

$rows_with_dates = array();

foreach($dates as $date) {
    $date = date('Y-m-d', $date);
    $rows_with_dates[$date] = $empty_row + array('date' => $date);
}

$connection = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS);
$statement = $connection->prepare("SELECT * FROM `stackoverflow` WHERE `date` BETWEEN '$from' AND '$to'");
$statement->execute();
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);

foreach($rows as $row){
    $rows_with_dates[$row['date']] = $row;
}

print_r($rows_with_dates);