Domanda

I have three tables in my DB, Student, Participant, and Activity. I'm trying to pull ALL the student names, activity names, and activity costs for all students participating in a certain activity. I'm wondering if this is possible. Here is the DB if you want to take a look: http://pastebin.com/QCsQfEKF

Basically I want a table that looks like this: (ex. data)

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

and I want the data selected by giving a certain activty that they all participate in.

I know how to do all of it except for the, selecting those who are all in a certain activity, part.

È stato utile?

Soluzione

You'll need several joins. Most importantly, to get the activity that they all participate in, you may use a separate joined alias (join more than once against participants and activities). One of the aliased joins is limited in the WHERE clause to only those having the desired activity, to return a list of student ids. Then you use that list to form the rest of your query.

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

Here it is in action: http://sqlfiddle.com/#!2/37860/6

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top