php - SQL 列出最喜欢的游戏数据库

标签 php sql mysql

所以我网站的主页显示了 PMP 的应用程序。用户可以用“喜欢”、“不喜欢”或“中立/无”对这些应用进行评分(默认情况下,每个应用都被评为中立/无。)

在主页上,我想按最大差异列出游戏(因此需要将喜欢和不喜欢的总数加在一起。)我很难编写 SQL 语句来正确执行此操作。

我的表结构是这样的:

appinfo:
   id;
   name;
   genre;
   ...

appinfo basically holds all the metadata for the app. Nothing about the rating.

Next, I have the apprating table:

apprating:
   username;
   app_id;
   rating;

This is where all the ratings are stored. Ratings are stored as a -1 (Dislike), 0 (Neutral/None), and 1 (Like). I was hoping with this structure it would be easier to setup the whole statement. Can anyone help me out with writing one? I ended up writing a ridiculously long one that doesn't sort properly or display the rating number.

SELECT appinfo.title, appinfo.description, appinfo.username, appinfo.genre 
FROM appinfo 
LEFT JOIN appratings ON appinfo.id=appratings.app_id 
GROUP BY appinfo.id 
ORDER BY SUM(appratings.rating) DESC

非常感谢您阅读本文,只需一条 SQL 语句并纠正我的邪恶 SQL 方式就很好了!

更新:

因此,在评级系统出现之前,我会有 SELECT 语句,然后在 PHP 中 mysql_fetch_array,然后循环并回显它们的详细信息,有效地让我执行以下操作:

...
<p class="description"><?php echo $gameinfo['description']; ?></p>
...

这会抓取正在运行的游戏的描述并进行回显。现在,描述仍然有效,但由于我现在有一个奇怪的系统,涉及使用 SUM 与我的喜欢/不喜欢以及 appinfo.id 和 appating.app_id 的 JOIN 语句,我现在遇到了问题

  1. 回显当前游戏的 ID(回显 $gameinfo['id'] 不会回显任何内容。)
  2. 如何获得喜欢/不喜欢的总和并进行回显?

更新2

SQL 语句允许我编写 echo $gameinfo['totalscore'] 来获取喜欢/不喜欢的差异,我只需将 appinfo.id 添加到选择能够回显 ID。

最佳答案

您的 GROUP BY 子句需要包含 SELECT 列表中未以某种方式聚合的所有列。您可能碰巧知道特定应用程序的描述、标题和其他详细信息不会更改,但数据库引擎不会更改,因此需要 了解每个选定的列是固定的(作为 GROUP BY 的一部分)还是聚合的(SUM、COUNT、MIN、MAX 等)

SELECT appinfo.title, appinfo.description, appinfo.username, appinfo.genre, 
    SUM(appratings.rating) AS totalscore
FROM appinfo LEFT JOIN appratings 
ON appinfo.id=appratings.app_id 
GROUP BY appinfo.title, appinfo.description, appinfo.username, appinfo.genre
ORDER BY totalscore DESC
;

关于php - SQL 列出最喜欢的游戏数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3983015/

相关文章:

javascript - 在 JavaScript 中获取 POST 事件而不是 Ajaxa (symfony4.1)

php - 如何在 Yii2 中获取同一查询中不同列的总和

javascript - 单击按钮时将 twig 中的 javascript 变量传递给 php Controller

mysql - Mysql 存储过程中循环内的 Select 语句

PHP MySQL 查询 - 添加

php - 在 Laravel 中使用 grpc,找不到 "Class ' Grpc\ChannelCredentials。”

sql - Postgresql to_timestamp 在包装 extract() 时返回不同的日期

sql - "materialize view"的最佳方式

php - 使用PHP+MySql的投票系统?

php - 如何在 PHP 中创建电视指南?