我有两张表afrostarprofiles和afrostarvvideos创建如下所示。 afrostarvideos中的artistid字段是afrostarprofiles的主要ID。我想要一个基于观点总和(afrostarvideo)和afrostarprofiles视图的最常见的afrostarprofile单一查询。我基本上需要一个算法或查询,根据来自afrostarvideos和afrostarprofiles的视图的视频的总观看次数对afrostarprofiles进行排名。这可能吗。我知道我可以用PHP处理sql结果这样做,但我认为有一个更有效的方式与MySQL。任何帮助表示赞赏
$ct_members="CREATE TABLE `afrostarprofiles` (".
"`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,".
"`name` TEXT NOT NULL ,".
"`country` TEXT NOT NULL ,".
"`piclocation` TEXT NOT NULL ,".
"`views` INT NOT NULL ,".
"`date` INT NOT NULL );";
mysql_query($ct_members);
$ct_members="CREATE TABLE `afrostarvideos` (".
"`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,".
"`name` TEXT NOT NULL ,".
"`url` TEXT NOT NULL ,".
"`views` INT NOT NULL ,".
"`artistid` INT NOT NULL ,".
"`date` INT NOT NULL );";
mysql_query($ct_members);
afrostarprofiles的表结构示例
4 Jose Chameleon Uganda afrostarpics/4.jpg 10 1287082754
3 Ziggy Dee Uganda afrostarpics/3.jpg 44 1286494407
afrostarvideo个人资料的例子
12 Tebamatila www 11 3 1287136275
13 Mamba Mtu www 14 3 1287136524
14 TECHNOLOGY www 15 4 1287170779
125 Jamila www 14 4 1287387760
答案 0 :(得分:1)
我认为你需要像
这样的东西SELECT `p`.*, SUM(`v`.`views`)+`p`.`views` AS `totalViews` FROM `afrostarprofiles` `p`
LEFT OUTER JOIN `afrostarvideos` `v` ON `p`.`id` = `v`.`artistid`
GROUP BY `p`.`id`
ORDER BY SUM(`v`.`views`)+`p`.`views` DESC
答案 1 :(得分:1)
使用:
SELECT t.*
FROM AFROSTARPROFILES t
JOIN (SELECT p.id,
SUM(p.views) + COALESCE(SUM(v.views), 0) AS total_views
FROM AFROSTARPROFILES p
LEFT JOIN AFROSTARVIDEOS v ON v.artistid = p.id
GROUP BY p.id) x ON x.id = t.id
ORDER BY x.total_views DESC