我该如何在SQL中运行此查询?

时间:2013-08-17 14:27:08

标签: php sql sql-order-by

我在游戏中有喜欢/不喜欢的表:id,game_id,类型(喜欢/不喜欢),时间

表示例:图像链接

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

$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;
    }
}

我想做这个查询,只能通过上周得到的喜欢来订购。

示例:如果游戏X有5个喜欢,游戏Y有6个喜欢,但游戏X得到这个星期三喜欢,游戏Y得到这个周2喜欢 - 游戏X将是第一个,游戏Y将是第二个。 / p>

非常感谢你!

2 个答案:

答案 0 :(得分:0)

添加一周的列,并按该顺序按该列排序。

像这样的东西

SELECT game_id
       ,DATEPART(wk, likeDate)
       ,count(*) as `likes_count`
FROM   likes 
WHERE  typ = 'like' 
AND    time > '{$time}' 
group by
       game_id
       ,DATEPART(wk, likeDate)
order by 
       2 DESC 
LIMIT  {$limit}

答案 1 :(得分:0)

您需要使用CASE:

SELECT `game_id`, COUNT(*) AS `likes_count` 
FROM `likes` 
WHERE `TYPE` = 'like' AND `TIME` > '{$time}' 
GROUP BY `game_id` 
ORDER BY COUNT(CASE WHEN `TIME` >= CURRENT_TIMESTAMP - INTERVAL '7' DAY END) DESC 
LIMIT {$limit}

你的DBMS似乎是MySQL,它支持INTERDER算术和ORDER中的计算。