0

我有喜欢/不喜欢游戏的表格:id, game_id, type(喜欢/不喜欢),time

表格示例:图片链接

这段代码给了我上周喜欢的游戏,按他们的喜欢计数排序:

$limit = 10;
$time = _time() - 60*60*24*7;
$games_id = array();
$games_id_query = $this->db->execQuery("SELECT `game_id`, count(*) as `likes_count` FROM `likes` WHERE `type` = 'like' AND `time` > '{$time}' group by `game_id` order by `likes_count` DESC LIMIT {$limit}");
$games_id_num = $games_id_query->num_rows;
if($games_id_num > 0) {
    while($row = $games_id_query->fetch_object()) {
        unset($row->likes_count);
        $games_id[] = (array) $row;
    }
}

我需要添加此代码。我想要一个更多的订单,这将是这个 game_id 的不喜欢计数,ASC。

我该怎么做?仅使用 SQL...非常感谢!

4

2 回答 2

0

你可能想要这样的东西:

SELECT `game_id`,
    SUM(IF(`type` = 'like', 1, 0)) AS likes_count,
    SUM(IF(`type` = 'dislike', 1, 0)) AS dislikes_count
FROM `likes`
WHERE `time` > '{$time}'
GROUP BY `game_id`
ORDER BY `likes_count` DESC, `dislikes_count` ASC
LIMIT {$limit}

话虽如此,请考虑使用准备好的语句和参数化查询,而不是直接将 PHP 变量嵌入 SQL 中。

有关更多信息,请参阅此问题:如何防止 PHP 中的 SQL 注入?

于 2013-06-12T00:31:45.790 回答
-1

从DESC更改为ASC,这是你想要的吗?

  SELECT game_id, count(*) as likes_count
    FROM likes
   WHERE type = 'like'
     AND time > '{$time}'
   group by game_id
   order by likes_count ASC LIMIT {$limit}
于 2013-06-12T00:26:53.147 回答