I’m working on a mySQL query that will hopefully add up sub totals of each table.
I have one table for members. This has their name, a unique ID and several other unrelated items. The other table is meant to keep track of their logged community service. Each member can be in it multiple times. The fields are uniqueID (foreign key to members), an auto_increment (for it’s primary), term, number of hours and location.
What I want this query to do is add a sum of each member’s hours for a given term. What I have is below, but unfortunately it only gives me the first member, with the total of each member. Any ideas?
SELECT fName, lName, SUM(hours)
FROM members M, communityService S
WHERE S.term = 'f2012' && M.onid = S.member
You are just missing a
GROUP BYclause to aggregate the sum perfName,lName:Most RDBMS other than MySQL would have reported a syntax error on your query, but MySQL has a unique default behavior of selecting, non-deterministcally, a matching row to fill out the rest of the columns in your aggregate that don’t appear in the
GROUP BYclause. That’s why you get the first row’slName, fName.Review the documentation on aggregate functions and the
GROUP BYclause.It is recommended to use an explicit
INNER JOINinstead of the implicit (comma-separatedFROM).