我的数据库表类似于:
id year month
1 2011 november
2 2011 november
3 2011 october
我需要创建一个查询,以便返回类似的内容:
2011
november
november
october
在php脚本中执行此操作的正确查询语法是什么?
以下是我使用的代码:
<?php
$uid = $_SESSION['uid'];
$sql = "SELECT year, GROUP_CONCAT(month) AS months FROM articles GROUP BY year";
$res = mysql_query ($sql) or die (mysql_error());
if (mysql_num_rows($res) > 0) {
while ($rows = mysql_fetch_assoc($res)) {
foreach ($rows AS $row) {
echo $row['year'] . "<br>";
$months = explode(",", $row['months']);
foreach ($months AS $m) {
echo $m . "<br>";
}
}
}
}
?>
答案 0 :(得分:2)
您可以使用GROUP_CONCAT()
返回以逗号分隔的月份列表:
SELECT year, GROUP_CONCAT(month) AS months GROM tbl GROUP BY year
Returns:
2011 november,november,october
或者只选择两列并处理代码中的显示/演示文稿:
SELECT year, month FROM tbl WHERE year = 2011
Returns
2011 november
2011 november
2011 october
在代码中,循环并仅显示更改时的年份。
更新由于代码示例似乎有理由......
// Results from above GROUP_CONCAT() query already fetched & stored in `$rowset`:
while ($row = mysql_fetch_assoc($res)) {
$rowset[] = $row;
}
// Now $rowset is a 2D array containing all rows.
foreach ($rowset as $row) {
// Output the year
echo $row['year'] . "\n";
// months are comma-separated via GROUP_CONCAT()
// explode them into an array
$months = explode(",", $row['months']);
foreach ($months as $m) {
// Output the months
echo $m . "\n";
}
}
答案 1 :(得分:0)
如果我正确地理解了你的问题,我认为一个简单的“ORDER BY”条款可以帮助你,类似于:
SELECT * FROM table_name ORDER BY year DESC
然后,使用脚本语言显示数据,一个好主意可能是(可能)获取第一行的年份,将其存储在时间变量中,然后遍历行并检查年份是否已更改如果有,则更改上述变量的值,如下所示:
$current_year = $data_set[0]['year'];
foreach ( $data_set as $data_row )
{
$current_year = ( $data_row['year'] != $current_year) ? $data_row['year'] : $current_year;
//Do something with it and/or the rest of the data
}
希望这有任何帮助。
干杯。