您將需要幾個連接。最重要的是,要獲得他們全部參與的活動,您可以使用單獨的加入別名(對participants
和activities
加入不止一次)。其中一個別名聯接在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
活動成本是所有活動的成本的總和? –
@MichaelBerkowski是的。 – carlgoodtoseeyou
這是SQLFiddle中的模式:http://sqlfiddle.com/#!2/7e0b2/1命中(構建模式,您可以開始查詢您的數據) –