按日期排序,仅对每个产品使用最新的行


Sorting by date, only with the newest row for each product

要创建一个表,我使用以下查询检索数据:

SELECT cId,cProductId,cDate,cInfo FROM tProduct ORDER BY cProductId ASC,cDate ASC;

很自然地,我简化了查询,但是您得到了值得注意的是,同一产品可能有许多记录,而我唯一感兴趣的记录是最新的,因此我如何排序查询:我只存储我在while循环中遇到的最后一行的信息。

while (($row = $result->fetch()) !== FALSE)
{
      if(!empty($row[0])){
          if(($table_row[1]!=$row[1])&&(!empty($table_row[0]))){
              //Display the last row saved
          }
          $table_row= array($row[0],$row[1],$row[2],$row[3]);
      }
}

现在我想为生成的html表实现一些排序选项。我将把排序信息存储在一个会话变量中。在排序选项中,我希望能够按日期排序。在按日期排序查询时,如何确保只检索每个产品的最新行?

您的查询中没有包含FROM子句。但是,假设您想要每个产品ID的最新行,您可以这样做:

SELECT cId,cProductId,cDate,cInfo
FROM tProduct t1
WHERE cDate = (SELECT max(cDate) FROM tProduct t2 where t1.cProductID = t2.cProductId)
ORDER BY cProductId ASC,cDate ASC;