简体   繁体   中英

How to find the maximum count and avg using mysql?

I need some help to build select query, have 2 tables games and votes. Need query that takes this game with max avg(rating) and count.

Games table is:

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;

and votes table:

   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;

use sub query..

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM