<?
require("config.php");
$result = mysql_query("select s_title, p_name, date from tbl_slist_info where publish='u' ORDER By date ") or die(mysql_error());
while($row=mysql_fetch_assoc($result))
{ ?>
<tr>
<td colspan="3"><?=$row['date']?></td>
</tr>
<tr>
<td><a href="g.php?title=<?=$row['s_title'] ?>"><?=$row['s_title'] ?></a></td>
<td><a href="p.php?title=<?=$row['p_name'] ?>"><?=$row['p_name'] ?></a></td>
</tr>
我想要一个mysql查询,这样我可以根据日期显示记录。假设在1月1日我有5个请求。1月2日,我有4个请求。IN this way
1-Jan
_____
A type1
B type1
C type2
D type1
E type3
2-Jan
____
W type4
X type1
Y type3
Z type5
可以在数据库级别这样做:
SELECT concat(date, concat(''n__________'n',
group_concat(concat(concat(name, ''t'), type) SEPARATOR ''n')))
FROM table_name
GROUP BY date;
您可能应该在应用程序级别执行此操作:当您遍历结果集时,检查当前日期是否与前一行的日期不同,以检测组更改。
根据问题
中添加的PHP代码进行编辑所以像这样:
$lastDate = null;
while($row = mysql_fetch_assoc($result)) {
if ($row['date'] != $lastDate) {
echo '<tr><td colspan="2">'.htmlspecialchars($row['date']).'</td></tr>';
$lastDate = $row['date'];
}
echo '<tr>';
echo '<td><a href="g.php?title='.urlencode($row['s_title']).'">'
.htmlspecialchars($row['s_title']) .'</a></td>';
echo '<td><a href="p.php?title='.urlencode($row['p_name']).'">'
.htmlspecialchars($row['p_name']).'</a></td>';
echo '</tr>';
}
您可以编写查询,但结果将是TABULAR。
结果将在列中重复
您可能希望这样做:
$cookedData = array();
while($row=mysql_fetch_assoc($result)) {
$cookedData[ $row['date'] ][] = $row;
}
foreach( $cookedData as $date => $relatedRecords ) {
// emit $date here
foreach( $relatedRecords as $oneRecord ) {
// emit $oneRecord['s_title'] etc, here
}
}