繁体   English   中英

使用group_concat?

[英]Group_concat use?

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

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

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

我希望通过给出他们都参与的某种活动来选择数据。

我知道该如何做,除了选择那些参加某项活动的人。

您将需要几个联接。 最重要的是,要获得他们都参与的活动,可以使用单独的联接别名(针对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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM