排名靠前评论

时间:2010-04-27 02:58:02

标签: mysql comments

如何使用PHP和mysql列出网站上评论最高页面的页面?

数据库的设置方式如下:

page_id | username | comment | date_submitted
--------+----------+---------+---------------
      1 |  bob     | hello   | current date
      1 |  joe     | byebye  | current date
      4 |  joe     | stuff   | date
      3 |  mark    | this    | a date

您如何查询它以便通过顶部评论页面对它们进行排序?

这是一个简单的查询开头(XXX是我认为需要帮助的区域):

$querycomments = sprintf("SELECT * FROM comments WHERE " .
    "XXX = %s ORDER BY XXX DESC",
    GetSQLValueString(????????????, "text"));

1 个答案:

答案 0 :(得分:3)

好吧,如果您正在寻找按照大多数评论的顺序列出页面的方法,我会按页面ID进行分组,然后按计数排序,例如:

select page_id, count(*)
from comments
group by page_id
order by 2 desc, 1 asc

从技术上讲,您不需要1 asc但我希望确保特定订单,即使在降序评论计数内也是如此。因此,如果出现大量具有相同评论计数的页面,您可以轻松地在该组中找到特定页面。换句话说,如果第7页有两条评论,而其他所有页面只有一条,那么您将获得(7,1,2,3,4,5,6,8,9)。如果没有1 asc,第1页到第6页和第8页到第9页可以按任何顺序返回,例如(7,6,2,4,3,9,1,8,5),它甚至可以在查询运行之间更改。

例如,构建一个示例表:

> DROP TABLE COMMENTS;
> CREATE TABLE COMMENTS (PAGE_ID INTEGER,COMMENT VARCHAR(10));
> INSERT INTO COMMENTS VALUES (1,'1A');
> INSERT INTO COMMENTS VALUES (2,'2A');
> INSERT INTO COMMENTS VALUES (1,'1B');
> INSERT INTO COMMENTS VALUES (3,'3A');
> INSERT INTO COMMENTS VALUES (2,'2B');
> INSERT INTO COMMENTS VALUES (1,'1C');
> INSERT INTO COMMENTS VALUES (3,'3B');
> INSERT INTO COMMENTS VALUES (3,'3C');
> INSERT INTO COMMENTS VALUES (3,'3D');

然后显示所有数据:

> SELECT * FROM COMMENTS
  ORDER BY 1, 2;
    +---------+---------+
    | PAGE_ID | COMMENT |
    +---------+---------+
    |       1 | 1A      |
    |       1 | 1B      |
    |       1 | 1C      |
    |       2 | 2A      |
    |       2 | 2B      |
    |       3 | 3A      |
    |       3 | 3B      |
    |       3 | 3C      |
    |       3 | 3D      |
    +---------+---------+

然后按降序评论计数运行一个选择组:

> SELECT PAGE_ID,COUNT(*) AS QUANT
  FROM COMMENTS
  GROUP BY PAGE_ID
  ORDER BY 2 DESC, 1 ASC;
    +---------+-------+
    | PAGE_ID | QUANT |
    +---------+-------+
    |       3 |     4 |
    |       1 |     3 |
    |       2 |     2 |
    +---------+-------+