I’m trying to join THREE tables.
The first table is transactions which contains details of “points” that students have earned. The relevant field here is Recipient_ID (the student receiving points).

The second table is purchases which contains details of “rewards” that students have purchased. The relevant fields here are Student_ID and Reward_ID.

The final table is rewards which details the rewards purchased. The relevant fields here are Reward_ID, Cost_to_User (the price the students pay for each reward which is being used to order the GROUP_CONCAT function) and Title.

The query I’m using is as follows:
SELECT
t.Recipient_ID AS `ID` ,
SUM( t.Points ) AS `Points Earned`,
SUBSTRING_INDEX( GROUP_CONCAT(DISTINCT r.Title ORDER BY r.Cost_to_User DESC SEPARATOR ', '),', ',3 ) AS `Rewards`
FROM `transactions` t
LEFT JOIN `purchases` p
ON t.Recipient_ID = p.Student_ID
LEFT JOIN `rewards` r
ON p.Reward_ID = r.Reward_ID
WHERE t.`Recipient_ID`
IN ( 90128, 90163, 33888, 34240, 137674 )
GROUP BY t.`Recipient_ID`
For some reason, the Points Earned output is vastly wrong. If I remove the LEFT JOIN on purchases, the Points Earned output is correct.
What is it about that join that’s sending my SUM command crazy?
EDIT: Please note that I require the LEFT JOIN commands as I’d like to display all students, including those that haven’t made any purchases. Further details found in this post.
Thanks in advance,
The problem is that you are getting multiple records from the transaction table with the join. You can use a subquery on the transaction table and it should fix this issue:
See SQL Fiddle with Demo
The strange total of the
pointsis coming from the join of the tables. Since you are joining the tables on only theRecipient_ID = Student_IDif there are records in both tables you are getting a cartesian number of results. So if you have 3 records for a student in thetransactionstable and 3 records in thepurchasestable the result will show 9 records for that student which alters the total.See SQL Fiddle with Demo