2

我的数据库表有 5 列:“id”、“date_visited”、“page_title”、“ip”和“total_views”。我无法显示 ORDER BY 'date_visited'。我的 PHP 查询是:

<?php
[...]
$query = "SELECT *,count(*) FROM table WHERE ip GROUP BY page_title";
$result = mysqli_query($link,$query) or die(mysqli_error($link). "Q=".$query);
if(!$result == 0) {
    while ($row = mysqli_fetch_array($result)) {
        $dataList_br .= '<tr>
                            <td>' .$row['date_visited']. '</td>
                            <td>' .$row['page_title']. '</td>
                            <td>' .$row['count(*)']. '</td>
                        </tr>';
    }
} else {
    $dataList_br .= '<p class="warning">No data found in database.</p>';
}
?>

输出时,显示[日期][页面标题]和[总浏览量]。请有人帮助我,我如何显示查询的最后日期,而不是现在它显示访问页面的第一天。

谢谢你。

4

3 回答 3

2

MySQL 对 的内容很宽容,GROUP BY如果列不在GROUP BY 但被SELECTed 中,MySQL 会稍微随意地为组返回一行。在您的情况下,它只是为您提供了每个组的第一行(最低日期)。

获取每个组的行的 page_nameMAX(date_visited)并将其与主表连接以从主表中提取剩余的列。

SELECT
  table.id,
  table.ip,
  table.total_views,
  maxdates.date_visited,
  maxdates.page_name,
  maxdates.thecount
FROM
  table
  JOIN (
    /* Subquery returns the aggregates to join against 
       the main table so other columns can be pulled in */
    SELECT 
      page_title, 
      MAX(date_visited) AS maxdate, 
      COUNT(*) AS thecount 
    FROM table 
    GROUP BY page_title
  ) maxdates
    ON table.page_name = maxdates.page_name 
       AND table.date_visited = maxdates.maxdate
于 2012-07-18T23:35:11.120 回答
0

你想用ORDER BY. 像这样:

$query = "SELECT *, count(*) 
            FROM table 
           WHERE ip 
        GROUP BY page_title 
        ORDER BY date_visited ASC";
于 2012-07-18T23:33:10.440 回答
0

试试这个“ORDER BY”:

$query = "SELECT date_visited, page_title,count(*) FROM table WHERE ip ORDER BY page_title ASC";
$result = mysqli_query($link,$query) or die(mysqli_error($link). "Q=".$query);
if(!$result == 0) {
    while ($row = mysqli_fetch_array($result)) {
        $dataList_br .= '<tr>
                            <td>' .$row['date_visited']. '</td>
                            <td>' .$row['page_title']. '</td>
                            <td>' .$row['count(*)']. '</td>
                        </tr>';
    }
} else {
    $dataList_br .= '<p class="warning">No data found in database.</p>';
}
于 2012-07-18T23:37:21.947 回答