如何使用mysql查找最大计数和平均值?

时间:2016-06-18 13:31:16

标签: php mysql laravel-5

我需要一些帮助来构建选择查询,有2个桌面游戏和投票。需要查询以最高平均(评级)和计数来获得此游戏。

游戏表是:

CREATE TABLE `games` (
  `id` int(10) UNSIGNED NOT NULL,
  `user_creator` int(10) UNSIGNED DEFAULT NULL,
  `name` varchar(30) COLLATE utf8_unicode_ci NOT NULL, 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

和投票表:

   CREATE TABLE `votes` (
  `id` int(10) UNSIGNED NOT NULL,
  `user_id` int(10) UNSIGNED DEFAULT NULL,
  `game_id` int(10) UNSIGNED NOT NULL,
  `rating` enum('1','2','3','4','5') COLLATE utf8_unicode_ci NOT NULL,

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

ALTER TABLE `votes`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `votes_user_id_game_id_unique` (`user_id`,`game_id`),
  ADD KEY `votes_game_id_foreign` (`game_id`);


ALTER TABLE `votes`
  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;


ALTER TABLE `votes`
  ADD CONSTRAINT `votes_game_id_foreign` FOREIGN KEY (`game_id`) REFERENCES `games` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `votes_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL;

1 个答案:

答案 0 :(得分:0)

使用子查询..

 Select g.name ,(rt /cnt) as avgrating ,cnt as gamecount
          from (
          select g.name ,sum(rating) as rt , count(v.game_id) as cnt
           from games  g join votes v on g.id =v.game_id
           group by g.name ) resut