如何通过此查询订购?

时间:2013-06-12 00:07:45

标签: php sql sql-order-by

我在游戏中有喜欢/不喜欢的表:idgame_idtype(喜欢/不喜欢),time

表示例:Image Link

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

$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 ...非常感谢!

2 个答案:

答案 0 :(得分: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中嵌入PHP变量。

有关详细信息,请参阅此问题:How can I prevent SQL injection in PHP?

答案 1 :(得分:-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}