表中的行顺序取决于相对表

时间:2012-01-25 14:23:12

标签: mysql sorting relational-database

我有两张桌子。一个有视频(lol_videos):

ID,title,Url,...

和一个命中表(lol_hits):

ID,videoID,时间戳

我想根据视频表中的视频数量(存储在lol_hits中)以及特定的时间范围内对视频进行排序。

我尝试了一些不同的东西,但我真的不能正确..到目前为止,我只是得到一些无用的mysql错误:(

$query = "SELECT `lol_videos`.*, COUNT(lol_hits.videoID) as hit_count".
" FROM `lol_videos`".
" WHERE published > $now AND pushed > 0".
" LEFT JOIN `lol_hits`".
" ON (`lol_hits`.videoID = `lol_videos`.ID)".
" ORDER BY hit_count DESC";
$result = mysql_query($query) or die(mysql_error());

任何人都有建议如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

这应该有效:

SELECT v.*, v2.numHits FROM (
    SELECT videoID, COUNT(ID) 'numHits' FROM lol_hits GROUP BY videoID
) AS v2 
JOIN lol_videos v ON (v.ID = v2.videoID)
ORDER BY v2.numHits DESC;

答案 1 :(得分:0)

这样的东西?

SELECT * FROM lol_videos
LEFT JOIN lol_hits
ON lol_videos.ID = lol_hits.videoID
ORDER BY lol_hits.hit_count DESC;