从mysql timestamp字段中选择Distinct month和year,并在php中回显它们

时间:2012-02-22 13:30:43

标签: php mysql

我的mysql表有一个createdOn列,其fieldstype为'timestamp',格式为2011-10-13 14:11:12

我需要的是显示,来自createdOn列的不同月份,年份。

我已经搜索了堆栈流,并且能够使用以下代码回显几个月,

*$sqlCommand = "SELECT DISTINCT MONTH(createdOn) AS 'Month' FROM videoBase ORDER BY createdOn DESC";
$query=mysqli_query($myConnection,$sqlCommand) or die(mysqli_error());
while($row = mysqli_fetch_array($query)) {
    $date = date("F", mktime(0, 0, 0, $row['Month']));
    echo ''.$date.' <br />';
}*

这将输出数月:

October
January

我需要的是输出格式:

October 2011
January 2012

任何人都可以告诉我,我应该在代码中做出哪些更改才能获得所需的输出。

由于

3 个答案:

答案 0 :(得分:8)

对于MySQL解决方案:

SELECT DISTINCT CONCAT(MONTHNAME(createdOn), ' ', YEAR(createdOn)) AS `Month`
FROM videoBase
ORDER BY createdOn DESC

这将获取MONTHNAME()函数和YEAR()函数的输出,并将它们之间的空格连接起来,如下所示:

October 2011
January 2012

答案 1 :(得分:6)

使用此:

$date = date("F Y", strtotime($row['Month']));

并且在您的查询中不选择月份,只需:

SELECT DISTINCT createdOn AS 'Month' FROM videoBase ...

所以它会是:

$comma = '';
while($row = mysqli_fetch_array($query)) {
    $date = $comma . date("F", mktime(0, 0, 0, $row['Month']));
    echo $comma . $date;
    $comma = ', ';
}

答案 2 :(得分:-1)

在下面尝试当年

 echo $date.date("Y");

如果您想要特定年份,则必须从数据库表中获取

由于