PHP MySQL 查询选择 DISTINCT 但按日期显示有限行

标签 php mysql database distinct

我需要有关 DISTINCT 的帮助。我想显示不同的行,但仅显示按日期排序的最新拖行(col3)

数据库中的此表示例:

+----+-----+------------+
|col1|col2 |col3        |
+----+-----+------------+
|A   |one  |1-jul-2013  |
|A   |two  |2-jul-2013  |
|A   |three|3-jul-2013  |
|A   |four |4-jul-2013  |
|A   |five |5-jul-2013  |
|B   |one  |1-jul-2013  |
|B   |two  |2-jul-2013  |
|B   |three|3-jul-2013  |
|B   |four |4-jul-2013  |
|B   |five |5-jul-2013  |
|B   |six  |6-jul-2013  |
|B   |seven|7-jul-2013  |
|B   |eight|8-jul-2013  |
+----+-----+-----+

$query = mysql_query('select * from table1 ORDER BY col3 DESC');
$results = array();

while($row = mysql_fetch_assoc($query)) {
    $col1= $row['col1'];

    // This is basically grouping your rows by col1
    if(!isset($results[$col1]))
        $results[$col1] = array();
    $results[$col1][] = $row;
}

echo "<tr>";

foreach($results as $col1=> $rows) {

    echo "<td>".$col1."</td>";

    foreach($rows as $row) {
        echo "<td>".$row['col2']."</td>";
    }

    echo"</tr>";
}

我需要对其进行一些修改..我想要不同并仅显示最新的 2 行

我希望显示如下:

A  |one  |two 

B  |one  |two 

最佳答案

以下是查询,

$query = mysql_query('select DISTINCT `column name` from table1 ORDER BY col3 DESC LIMIT 2');

关于PHP MySQL 查询选择 DISTINCT 但按日期显示有限行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26409873/

相关文章:

php - 学说查询 WHERE IN - 多对多

mysql - 连接多个 mysql 表

java - MySQL J 连接器

php - 在 HTML 下拉 <select> 列表中显示数据库表值

ios - 将内容从 Firebase 拉入 Swift 的问题

database - 我应该在数据库或数据访问层生成一个复杂的对象吗?

php - 如何在 MySQL 中通过一次选择为每个 'category' 获取 5 条记录?

php - MySQL、PHP 和 PDO 中的高效后代记录删除

php - 通过内部值获取数组元素

php - 在 wampserver 上复制数据库和网站文件夹