我有一个名为events的mysql表,其中包含以下字段:id,date和name。 日期字段的格式为yyyy-mm-dd hh :: mm:ss edit:表示它采用日期时间格式
我想在白天对活动进行分组,我不知道如何处理这个问题 - 有没有办法只从田间选择月份和日期?或者在我选择所有“事件”之后我应该使用PHP
我的最终目标是拥有这样的东西:
March 10th:
event1,
event2
March 11th:
event4,
event5
我找到MySQL select using datetime, group by date only,但我不确定如何实现它:
SELECT DATE_FORMAT(date, '%H%i'), DATE_FORMAT(date, '%M %D'), name FROM events ORDER BY date
谢谢!
编辑:
最终使用了这个:
$sql = "select team1, team2, DATE_FORMAT(date,'%Y-%m-%d') as created_day FROM games WHERE attack = '1' GROUP BY created_day";
$result = mysql_query($sql);
$curDate = "";
while (list($team1, $team2, $date) = mysql_fetch_row($result))
{
if ($date != $curDate)
{
echo "$date --------\n";
$curDate = $date;
}
echo "game data: $team1 $team2";
}
答案 0 :(得分:1)
如果您使用group by
,则不会获得一行。{p>因此,通过Group By AFAIK无法实现您想要的方式。
$query = "SELECT distinct(DATE_FORMAT(date, '%M %D')) as d FROM yourtable";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
echo $row['d']
$sql = "SELECT * FROM yourtable WHERE DATE_FORMAT(date, '%M %D')='$row[d]'";
$rs = mysql_query($query);
while($r = mysql_fetch_assoc($rs)) {
echo "event";
}
}
答案 1 :(得分:1)
你确实应该使用php来完成这项工作。但由于大多数当前系统都是显示器中的sepate逻辑,我只使用一次传递而不是(NUMBER OF DAYS + 1)个SELECT,并准备一个我稍后可以重复用于显示的数组。
$query = "SELECT DATE_FORMAT(date, '%M %D') as d, name FROM yourtable ORDER BY date";
$foo=array();
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
//some logic to test if it's safe to add the name
$foo[$row['d']][]=$row['name'];
}
然后当我需要它时(通过模板或“视图”)
foreach($foo as $date => $events) {
echo $date . ":\n\t";
echo implode(",\n\t", $events);
echo "\n";
}
因此它符合您为自己设定的格式。
希望有所帮助
答案 2 :(得分:0)
我想从那个问题/答案中,你可以得到类似的东西
March 10th, event1
March 10th, event2
March 11th, event4
March 11th, event5
它并不真正将“日期”组合为您的愿望,但我认为您可以使用php继续此结果。
答案 3 :(得分:0)
我同意Kharaone,与显示器分开的逻辑。话虽这么说,我认为类似于这个查询的东西可能就是你要找的东西:
SELECT A FROM
(
SELECT DATE_FORMAT(date,'%M %D:') AS A, DATE(date) AS B, 1 AS C FROM games GROUP BY DATE(date)
UNION ALL
SELECT name AS A, DATE(date) AS B, 2 AS C FROM games
) X
ORDER BY B, C ASC;