如何在php中尽可能高效地对数据进行计数和排名

发布于 2024-07-19 04:29:22 字数 379 浏览 8 评论 0原文

我对编程并不陌生,但对 MySQL 和 PHP 很陌生。 我想知道执行以下操作最有效的方法是什么。 我不需要实际的代码,只需要步骤。

我有一个用户评论列表,简单地说:

USER    REVIEW  
Bob     nice
John    good
Fred    bad
Bob     poor
Bob     the best
Fred    medicre
Bob     shiny

我希望能够创建一个发表最多评论的评论者列表,即

USER REVIEWS
Bob  4
Fred 2
John 1

什么是解决此问题的最佳方法,以最有效的方式

欢呼!

I'm not new to programming, but i'm new to MySQL and PHP. I'm wondering what the most efficient way of doing the following. I dont need the actual code, but just the steps.

I have a list of user reviews, lets say simply:

USER    REVIEW  
Bob     nice
John    good
Fred    bad
Bob     poor
Bob     the best
Fred    medicre
Bob     shiny

I want to be able to create a list of the reviewers that have made the most reviews, ie

USER REVIEWS
Bob  4
Fred 2
John 1

WHat's the best way of going about this, in the most efficient way

cheers!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柠栀 2024-07-26 04:29:22

正如您的查询:

SELECT user, COUNT(*) AS reviews
FROM <table name>
GROUP BY user
ORDER BY reviews DESC;

As your query:

SELECT user, COUNT(*) AS reviews
FROM <table name>
GROUP BY user
ORDER BY reviews DESC;
云之铃。 2024-07-26 04:29:22

有时,程序员用代码来解释自己会更容易:

// Credit to Chad Birch for the query...
$query = "SELECT user, COUNT(*) AS reviews 
          FROM <table name>
          GROUP BY user
          ORDER BY reviews DESC";

$res = mysql_query($query);
if(mysql_num_rows($res) > 0) {
    $res_array = mysql_fetch_assoc($res);
    $list = "<h1>USER REVIEWS</h1>\n";
    foreach($res_array as $user) {
        $list .= $user['user'].' '.$user['reviews']."<br />\n";
    }
}

echo $list;

所以,基本上,9/10 次,最好让 SQL 来做排序之类的事情,因为它在做这样的事情上效率更高。

  1. 执行 SQL 查询并让它对结果进行排序
  2. 让 PHP 检查是否有返回结果。
  3. 让 PHP 将结果转换为数组/对象
  4. 让 PHP 遍历数组,提取所需的内容
  5. 打印您想要的输出。

Sometimes it's just easier for programmers to explain themselves with code:

// Credit to Chad Birch for the query...
$query = "SELECT user, COUNT(*) AS reviews 
          FROM <table name>
          GROUP BY user
          ORDER BY reviews DESC";

$res = mysql_query($query);
if(mysql_num_rows($res) > 0) {
    $res_array = mysql_fetch_assoc($res);
    $list = "<h1>USER REVIEWS</h1>\n";
    foreach($res_array as $user) {
        $list .= $user['user'].' '.$user['reviews']."<br />\n";
    }
}

echo $list;

So, basically, 9/10 times, it's best to let SQL do the sorting and stuff because it's just way more efficient at stuff like that.

  1. Do SQL query and let it sort your results
  2. Let PHP check to see if there are any results returned.
  3. Let PHP convert results to array/object
  4. Let PHP tranverse array, extract needed content
  5. Print your desired output.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文