【问题标题】:How to find the maximum count and avg using mysql?如何使用mysql找到最大计数和平均值?
【发布时间】:2016-06-18 13:31:16
【问题描述】:

我需要一些帮助来构建选择查询,有 2 个表游戏和投票。需要以最大 avg(rating) 和 count 获取该游戏的查询。

游戏桌是:

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;

【问题讨论】:

    标签: php mysql laravel-5


    【解决方案1】:

    使用子查询..

     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
    

    【讨论】:

      猜你喜欢
      • 2013-12-23
      • 1970-01-01
      • 2014-11-20
      • 2014-07-03
      • 2013-05-02
      • 2016-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多