在MySQL中如何从两个表中编写SQL?

时间:2014-02-05 04:54:03

标签: mysql sql

每次用户玩游戏时,我都会在表game_log中插入一个新行。

create table game_log (
  userId int, 
  gameId int
);

insert into game_log (userId, gameId) values (1, 100);
insert into game_log (userId, gameId) values (1, 101);
insert into game_log (userId, gameId) values (2, 100);
insert into game_log (userId, gameId) values (2, 101);    
insert into game_log (userId, gameId) values (2, 102);
insert into game_log (userId, gameId) values (3, 100);
insert into game_log (userId, gameId) values (3, 101);
insert into game_log (userId, gameId) values (3, 102);

我想根据玩过的总游戏创建一个用户分布报告。也就是说有多少人玩过1场比赛,2场比赛,3场比赛等等。

select Nbr, count(*)
  (select count(*) as 'Nbr', UserId
  from game_log
  group by UserId
  ) as tbl
group by Nbr;

我希望得到这样的报告:

Results:
| 2 | 1 |
| 3 | 2 |

换句话说,有1个人玩了2场比赛。有2人玩了3场比赛。

但我得到一个sql语法错误,任何想法为什么?

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(select count(*) as 'Nbr', UserId
  from game_log
  group by UserId
  ) as tbl
g' at line 2

1 个答案:

答案 0 :(得分:5)

缺少FROM

SELECT Nbr, count(*)
FROM (SELECT count(*) as 'Nbr', UserId
      FROM game_log
      GROUP BY UserId
      ) as tbl
GROUP BY Nbr;

演示:SQL Fiddle