如何在MySQL中结合GROUP BY和JOIN语句?

时间:2019-06-13 16:08:27

标签: mysql mysql-workbench

我试图将我在一个表上运行的查询与另一表上的某些列组合。我运行的查询通过以下方式为我计算出总值:

SELECT security.Loan_id
     , SUM(security.SecMktValue) AS TotalSecMktValue
  FROM security 
 GROUP 
    BY Loan_id
 ORDER 
    BY loan_id ASC;

然后我尝试通过以下方式将查询与另一个表中的列连接起来:

SELECT loans.Loan_id, loans.TotalLoanAmt
FROM loans
JOIN(SELECT SUM(security.SecMktValue) AS TotalSecMktValue,security.Loan_id
FROM security
GROUP BY Loan_id ASC)
ON loans.Loan_id = security.Loan_id;

但是,这不会运行,因为它说我的SQL语法有错误,即使红色下划线都没有。有人知道为什么吗?

3 个答案:

答案 0 :(得分:1)

如果我让您问对了,那么这应该可以工作:)

SELECT security.Loan_id,SUM(security.SecMktValue) AS TotalSecMktValue
  FROM security security
  JOIN loans loan 
  ON loans.Loan_id = security.Loan_id
  GROUP BY Loan_id ASC

答案 1 :(得分:0)

您缺少别名:

SELECT loans.Loan_id, loans.TotalLoanAmt
FROM loans
JOIN(
    SELECT SUM(security.SecMktValue) AS TotalSecMktValue,security.Loan_id
    FROM security
    GROUP BY Loan_id ASC
    ) security -- <-- here
ON loans.Loan_id = security.Loan_id;

答案 2 :(得分:0)

MySQL需要将别名分配给派生表(即与内联视图关联的相关名称)。限定符wrapped_env = WrappedEnv(env, True) runner = Runner(agent=agent, environment=wrapped_env) runner.run(episodes=1, max_episode_timesteps=2000) print("Stats: ", runner.episode_rewards, runner.episode_timesteps, runner.episode_times) agent.save_model(directory='E:\pommerman\playground-master\save file\DQN-p', append_timestep=False) try: runner.close() except AttributeError as e: pass 超出了内联视图的范围,即它不是外部查询中的有效引用。)

这里是一个示例,将别名security分配给派生表。请注意,在外部查询中,对内联视图中列的引用使用t

进行限定。
t.