mysql – SQL ORDER BY Idea

我有两张桌子.

上传者 – 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>";
    }
}

最佳答案 只需使用聚合添加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
点赞