我正在开发一个视频游戏库存网站。这是我的数据库表的简化版本以及一些示例数据:
CREATE TABLE `platforms` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(16) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `platforms` VALUES(1, 'Nintendo');
INSERT INTO `platforms` VALUES(2, 'Super Nintendo');
INSERT INTO `platforms` VALUES(3, 'Nintendo 64');
--
CREATE TABLE `games` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`platform_id` int(10) unsigned NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
INSERT INTO `games` VALUES(1, 1, 'Super Mario Bros.');
INSERT INTO `games` VALUES(2, 1, 'Super Mario Bros. 2');
INSERT INTO `games` VALUES(3, 2, 'Super Mario World');
INSERT INTO `games` VALUES(4, 2, 'Super Mario Kart');
INSERT INTO `games` VALUES(5, 3, 'Super Mario 64');
INSERT INTO `games` VALUES(6, 3, 'Mario Kart 64');
--
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(64) NOT NULL,
`password` varchar(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `users` VALUES(1, 'john_doe', '$2a$10$cQhc4VAXVMEyC1tA.VRoWunpNVi7392adacT/weVBzu6XGI6.Jx/K');
INSERT INTO `users` VALUES(2, 'jane_doe', '$2a$10$Ot2BmlT14hKDxHGIV8jBx.lW76HCWdwuOhNGIYrJO5O7BEtDUWLWu');
--
CREATE TABLE `games_users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`game_id` int(10) unsigned NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`created` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
INSERT INTO `games_users` VALUES(1, 1, 1, '2013-04-12 12:18:09');
INSERT INTO `games_users` VALUES(2, 3, 1, '2013-04-12 12:18:42');
INSERT INTO `games_users` VALUES(3, 4, 1, '2013-04-12 12:19:13');
INSERT INTO `games_users` VALUES(4, 2, 2, '2013-04-12 12:19:32');
如您所见,john_doe 拥有 1 款 Nintendo 游戏(超级马里奥兄弟)、2 款 Super Nintendo 游戏(Super Mario World 和 Super Mario Kart)和 0 款 Nintendo 64 游戏。jane_doe 有 1 款任天堂游戏(超级马里奥兄弟 2)、0 款超级任天堂游戏和 0 款任天堂 64 游戏。
我想编写一个特定于用户的查询,该查询将列出所有控制台,并列出用户在每个控制台上拥有的游戏数量。
这就是 john_doe 的结果:
platform.id: 1
platform.name: Nintendo
game_count: 1
platform.id: 2
platform.name: Super Nintendo
game_count: 2
platform.id: 3
platform.name: Nintendo 64
game_count: 0
这是 jane_doe 的结果:
platform.id: 1
platform.name: Nintendo
game_count: 1
platform.id: 2
platform.name: Super Nintendo
game_count: 0
platform.id: 3
platform.name: Nintendo 64
game_count: 0
我怎样才能做到这一点?