2016-06-18 16 views
0

私は選択クエリを構築するにはいくつかの助けが必要です、2テーブルのゲームと投票を持っています。最大平均(評価)とカウントでこのゲームにかかるクエリが必要です。mysqlを使って最大数と平均を見つける方法は?

ゲームテーブルです:

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; 

答えて

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 
関連する問題