Group_concat使用?

时间:2014-04-27 23:19:03

标签: mysql group-concat

我的数据库中有三个表,学生,参与者和活动。我正在尝试为参与某项活动的所有学生提取所有学生姓名,活动名称和活动费用。我想知道这是否可行。如果你想看一下这就是数据库:http://pastebin.com/QCsQfEKF

基本上我想要一个看起来像这样的表: (例如数据)

Name  /         Activities        /Activities Cost
carl  /basketball, golf           /$500
jane  /pottery, skydiving, golf   /$600

我希望通过提供他们都参与的特定活动来选择数据。

我知道如何做所有这些,除了选择那些属于特定活动的人,部分。

1 个答案:

答案 0 :(得分:1)

你需要几个连接。最重要的是,要获得他们都参与的活动,您可以使用单独的加入别名(针对participantsactivities加入多次)。其中一个别名连接在WHERE子句中仅限于具有所需活动的连接,以返回学生ID列表。然后使用该列表构成查询的其余部分。

SELECT
  s.stu_fname,
  s.stu_lname,
  GROUP_CONCAT(a.act_name) AS Activities,
  SUM(a.act_fee) AS `Activities Cost`
FROM
  /* These first two joins doing go into the SELECT list.
     They are used to get the list of students with your desired activity
     and will be used in the WHERE clause */
  participant plimit
  INNER JOIN activity alimit ON plimit.act_id = alimit.act_id
  /* Only include those students from the first 2 joins */
  INNER JOIN student s ON plimit.stu_id = s.stu_id
  /* Then join through the participants to get all activities for those students */
  INNER JOIN participant p ON s.stu_id = p.stu_id
  /* And to get the names of the activities */
  INNER JOIN activity a ON p.act_id = a.act_id
/* Limit to only those students with golf */
WHERE alimit.act_name = 'pottery'
/* Apply the aggregate GROUP BY to the rest of the columns in the SELECT */
GROUP BY 
  s.stu_id,
  s.stu_fname,
  s.stu_lname

这里有效:http://sqlfiddle.com/#!2/37860/6