打印每个类别最受瞩目的视频

时间:2018-02-11 19:57:39

标签: php mysql sql arrays

我有两张桌子

video(id,macro_categoria,categoria,titolo)

video_logs(id,idvideo,logs)

(存储观看视频的次数)。 这种关系很多id=>idvideo 我想要一个这样的结果:

  macro_categoria:one {
          [1]=> video 1 details
          [2]=> video 2 details
          [3]=> video 3 details
          [4]=> video 4 details
        }
  macro_categoria:two {
          [1]=> video 1 details
          [2]=> video 2 details
          [3]=> video 3 details
          [4]=> video 4 details
        }

上面的数组为每个macro_categoria打印了四个观看最多的视频。观看视频的次数是从表video_logs的日志中获取的。目前我正处于这个状态,我被卡住了:

SELECT c.macro_categoria,c.id, Count((v.id)) as Views
 FROM video c,video_log v
 WHERE c.id = v.idvideo
 GROUP BY c.id 
 ORDER BY Views DESC LIMIT 4

这回声:

[0] => Array
        (
            [macro_categoria] => macro2
            [id] => 11
            [Views] => 47
        )

[1] => Array
    (
        [macro_categoria] => macro1
        [id] => 12
        [Views] => 23
    )

1 个答案:

答案 0 :(得分:0)

以下是一个选择具有计数的每个类别的查询:

SELECT videos.id, cats.macro_categoria, videos.titolo, IFNULL(views.cnt, 0) AS cnt 
FROM (SELECT DISTINCT macro_categoria FROM `video`) cats 
JOIN (SELECT id, macro_categoria, titolo FROM video) videos ON videos.macro_categoria = cats.macro_categoria 
LEFT JOIN (SELECT idvideo, COUNT(idvideo) as cnt FROM video_log GROUP BY idvideo) `views` ON `views`.idvideo = videos.id 
ORDER BY cats.macro_categoria, cnt DESC

在这里,我们从类别列表开始,(INNER)将视频加入这些类别,然后LEFT加入视图计数,这样我们仍然可以获得NULL结果,这样您就可以知道哪里没有视图。然后按类别和视图排序,降序。

如果你想在PHP中获得每个类别的四个顶级成员,你可以使用如下逻辑(一点伪代码):

$result = DB::query($sql);
$byCategory = [];
while ($row = DB::fetchAssoc($result)) {
    // Create array to hold category
    if (!isset($category[$result['macro_categoria']))
        $category[$result['macro_categoria'] = [];

    // Store record
    $byCategory[$result['macro_categoria']][] = $result;
}

// Trim results per category
foreach ($byCategory AS $cat=>$data)
    $byCategory[$cat] = array_slice($data, 0, 4);

array_slice抓住每个类别的四个第一要素。只要结果集从服务器中正确排序,这将返回最高值。