MYSQL将两个表与自己创建的列合并

时间:2018-10-10 06:54:12

标签: mysql

嗨,我对这两个表有两个不同的查询,如下所示:

表1:

enter image description here

表2:

enter image description here

[1] select exerciseId, sum(frustrated = 'Y') as Frustrated,
sum(frustrated = 'N') as NotFrustrated
from selfreportfrustration
group by exerciseId;

[2] SELECT exercisesId, count(*) as total FROM exerciseprogress GROUP BY 
exercisesId;

如何将这两个查询合并为一个查询,这样我就可以拥有一个包含4列的单一视图?如果我没记错的话,exerciseId和ExercisesId都是相同的,因此可以将它们加入。谢谢您的时间!

2 个答案:

答案 0 :(得分:0)

使用左联接

select a.*, b.total 
from

(select exerciseId, sum(frustrated = 'Y') as Frustrated,
sum(frustrated = 'N') as NotFrustrated
from selfreportfrustration
group by exerciseId) a 

left join 
(SELECT exercisesId, count(*) as total FROM exerciseprogress GROUP BY 
exercisesId) b 
on a.exerciseId=b.exercisesId

答案 1 :(得分:0)

这是一个查询:

select main.exerciseId, sum(main.frustrated = 'Y') as Frustrated,sum(main.frustrated = 'N') as NotFrustrated,
(SELECT count(*) FROM exerciseprogress WHERE exercisesId = main.exerciseId) as total
from selfreportfrustration AS main
group by exerciseId;