因此,我需要一个MySQL
查询表child
,然后每个孩子都有活动。活动在相关表中。我想显示每个孩子的名字(fname +sname)
及其活动数量。
这是我到目前为止的内容,但它返回错误:
CREATE TABLE Childactivities AS
SELECT CONCAT(`Child`.`child_fname`,' ',`Child`.`child_sname`) AS `name`
FROM Child
count activity_id as `activities`
FROM Childactivity
LEFT JOIN Childactivity
ON Childactivity.child_id=Child.child_id
GROUP BY Child.child_id
输出应该在两列中:子名称(名字和姓氏),以及 相关活动。 (对于没有相关活动的孩子,该值为0。)
请查看此database diagram。
答案 0 :(得分:1)
使用LEFT JOIN
获取所有有或没有活动的孩子
SELECT CONCAT(`Child`.`child_fname`,' ',`Child`.`child_sname`) AS `name`, COUNT(activity.activity_id)
FROM Child
LEFT JOIN Childactivity ON Childactivity.childId = Child.child_id
LEFT JOIN activity ON activity.activity_id = Childactivity.activity_id
GROUP BY CONCAT(`Child`.`child_fname`,' ',`Child`.`child_sname`)
答案 1 :(得分:1)
对于连接和函数count(),查询中存在语法错误。
试试这个:
CREATE TABLE Childactivities AS
SELECT
CONCAT(c.child_fname,' ',a.child_sname) AS `name`,
COUNT(a.activity_id) AS `activities`
FROM Child c LEFT JOIN Childactivity a
ON a.child_id = c.child_id
GROUP BY c.child_id, `name`
答案 2 :(得分:0)
感谢您的所有帮助人员,我在这里发布了工作结果:
SELECT CONCAT(`Child`.`child_fname`,' ',`Child`.`child_sname`) AS `name`,
COUNT(Activity.activity_id)
FROM Child
LEFT JOIN Childactivity ON Childactivity.child_id = Child.child_id
LEFT JOIN Activity ON Activity.activity_id = Childactivity.activity_id
GROUP BY CONCAT(`Child`.`child_fname`,' ',`Child`.`child_sname`)