我一起用php,mysql和html来显示表格。 但是我希望按时间戳对项目进行排序,并将具有相同ID的项目组合在一起。 例如:
未排序的表格:
timestamp id name description
14:02 2 Hans Is very nice!
12:01 3 Jürgen Is very bad!
10:03 2 Hans Again good.
11:08 6 Anna BAD!
06:09 11 Peter Good.
右排序表:
timestamp id name description
06:09 11 Peter Good.
10:03 2 Hans Again good.
14:02 2 Hans Is very nice!
11:08 6 Anna BAD!
12:01 3 Jürgen Is very bad!
错误的排序表:
timestamp id name description
06:09 11 Peter Good.
10:03 2 Hans Again good.
11:08 6 Anna BAD!
12:01 3 Jürgen Is very bad!
14:02 2 Hans Is very nice!
我认为必须有一个内部联接:首先找到具有最早时间戳的项目。然后查看是否有另一个具有相同ID的项目:如果是,则必须将其放在具有最旧时间戳的项目旁边。
答案 0 :(得分:1)
如果您对使用两者 MySQL 和 PHP的答案感兴趣,那么这将达到您想要的效果。
<强>的MySQL 强>
SELECT `timestamp`, `id`, `name`, `description` FROM TableName ORDER BY `timestamp` DESC;
<强> PHP 强>
// execute your query and put the results into $dateSortedArray
// I am assuming you know how to do this
$outterArray = array();
// iterate through each row of the $dateSortedArray
foreach($dateSortedArray as $row)
{
// this is where we're doing the 'sub ordering' part
// I'm pre-pending 'id_' in the index so that it is string-based
if(!isset($outterArray["id_".$row["id"]]))
{
// if we do not see this id in our result array yet,
// add a new array with this row in it
$outterArray["id_".$row["id"]] = array($row);
}
else
{
// if we have already see this id before,
// add the current row to the array with this id-based index
$outterArray["id_".$row["id"]][] = $row;
}
}
// iterate through our result array
foreach($outterArray as $innerArray)
{
foreach($innerArray as $innerRow)
{
// simply dump out each line, comma-seperated
echo implode(",", $innerRow) . "\r\n";
}
}
答案 1 :(得分:-1)
试试这个:
子查询将返回具有NewTimeStamp的临时列,该列对于相同的id列值将相同。
SELECT
X.timestamp,
X.Id,
X.name,
X.description
FROM
(
SELECT TMain.timestamp,TMain.id,TMain.name,TMain.description
(
CASE WHEN ((SELECT COUNT(1) FROM @tblTest T WHERE T.Id=TMain.Id))>0
THEN (SELECT TOP(1) timestamp FROM @tblTest T WHERE T.Id=TMain.Id ORDER BY timestamp)
ELSE timestamp END
) AS NewTimeStamp FROM @tblTest TMain
)X
ORDER BY X.NewTimeStamp,X.timestamp