4

我有两张桌子。上传者 - id、名称、图标、视图 视频 - id、上传者、视频、视图

上传者列用作视频上传者的参考。因此,我可以使用 sum() 函数来计算每个用户从他的所有视频中总共获得了多少观看次数。现在我想按 desc 总视图对这些用户进行排序。

我该怎么做呢?这是我到目前为止的代码......

//Retrieve data from the database
$fkbar = mysql_query("SELECT * FROM freaks");
while($fkrow = mysql_fetch_array($fkbar))

//Echo Theme Template on pages  
{   
    $frkid = $fkrow['id'];
    $viewq = mysql_query("SELECT SUM(views) AS vw FROM videos WHERE ref1='{$frkid}' OR ref2='{$frkid}' OR ref3='{$frkid}'");
    while($viewcnt = mysql_fetch_array($viewq))
    {       

        $viewcount = $viewcnt['vw'];

            echo "<div class='diva' id='{$viewcount}'>";
            echo "<div class='inner-diva'><a href='/mobile/freaks/?i={$fkrow['id']}'>";
            echo "<img id='{$fkrow['id']}' class='dvBarIco' src='/assets/ico/{$fkrow['icon']}' height='80px'></a></div>";
            echo "</div>";
    }
}
4

2 回答 2

1

只需ORDER BY使用聚合添加一个子句:

ORDER BY SUM(views) DESC

根据您的评论,您可以在第一个使用子查询进行排序:

SELECT *
FROM freaks f
ORDER BY (SELECT SUM(views) FROM videos WHERE ref1=f.id OR ref2=f.id OR ref3=f.id) DESC

您也可以通过连接来执行此操作,但这OR可能会使事情变得复杂:

SELECT f.*, COALESCE(v.views, 0) total_views
FROM freaks f
LEFT OUTER JOIN (
    SELECT SUM(views) views, id
    FROM (
        SELECT views, ref1 AS id
        FROM videos
        UNION ALL
        SELECT views, ref2 AS id
        FROM videos
        UNION ALL
        SELECT views, ref3 AS id
        FROM videos
    ) x
    GROUP BY id
) v ON f.id = v.id
ORDER BY total_views DESC
于 2013-10-11T03:18:46.380 回答
1

尝试使用子选择来获取总和,这将结合您的两个查询,并为您提供跨两个表排序的选项,而不是每次都在第二个查询中排序。

$fkbar = mysql_query(
"SELECT 
    (SELECT SUM(views) AS vw FROM videos WHERE videos.ref1=freaks.id OR videos.ref2=freaks.id OR videos.ref3=freaks.id) as total_views, 
* FROM freaks ORDER BY total_views DESC");
于 2013-10-11T03:22:16.867 回答