计算每个人分配给的活动

时间:2018-07-31 14:06:04

标签: mysql sql database

我有一个问题,我需要能够计算孩子已注册要做的活动数量。目前,我有这个:

SELECT child_fname, activity_id
FROM Child
LEFT JOIN Activity
ON Activity.ActivityID=activity.activity_id
ORDER BY Child.child_fname;

我的桌子是这样的:

子表

  • child_firstname
  • child_secondname
  • child_age

活动

  • activity_id
  • activity_name
  • activity_price

ChildActivity

  • child_id
  • activity_id

我正在寻找类似的东西

  • [姓名] [活动数量]
  • Sam Smith 5
  • 瑞秋·史密斯4

我尝试使用JOIN,但我的查询没有更新新数据

2 个答案:

答案 0 :(得分:0)

使用INNER JOIN

SELECT Child.child_firstname, COUNT(Activity.activity_id)
FROM Child
INNER JOIN Activity ON Activity.activity_id=ChildActivity.activity_id
INNER JOIN ChildActivity ON ChildActivity.child_id=Child.child_id
ORDER BY Child.child_firstname;

Ps:请检查列名和表格。

示例 SQL Inner-join with 3 tables?

答案 1 :(得分:0)

这就是我想要的

SELECT child_fname as Name, count(activity_id) as `Number of Activities`
FROM Child
LEFT JOIN ChildActivity
ON ChildActivity.child_id=Child.child_id
GROUP BY Child.child_id
ORDER BY COUNT(activity_id) DESC;

重点是您想将ChildChildActivity一起加入并按Child分组,这样,Child中的每条记录都会得到一个活动计数。