【问题标题】:In MySQL how to write SQL from two tables?在 MySQL 中,如何从两个表中编写 SQL?
【发布时间】:2014-02-05 13:02:40
【问题描述】:

每次用户玩游戏时,我都会在 table 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

【问题讨论】:

  • 如果我们不知道发生了什么错误,我们怎么知道?
  • 听起来你想为此使用连接
  • 你的预期结果对我来说没有意义,每个userID 玩 3 场比赛...
  • Goat CO,如果您查看插入语句,请注意 userId 1 只玩了 2 场比赛。

标签: mysql sql


【解决方案1】:

只是缺少FROM

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

演示:SQL Fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-29
    • 2012-05-13
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多