tags:

views:

23

answers:

1

On the Members table are columns "MemberID" and "PointsEarned".

I want to update the PointsEarned column from the result of this query:

SELECT m.MemberID, m.UserName, 
     ( (SELECT COUNT(*) FROM EventsLog as e WHERE e.MemberID=m.MemberID AND e.EventsTypeID=2)*10 ) + 
     ( (SELECT COUNT(*) FROM EventsLog as e WHERE e.MemberID=m.MemberID AND e.EventsTypeID=3)*3 ) +
     ( (SELECT COUNT(*) FROM ChatMessages as c WHERE c.MemberID=m.MemberID)*.1 )
     as PointsEarned
   FROM Members as m

Can anybody tell me how I should do it with a single query?

Thanks!

+1  A: 

You may want to try the following:

UPDATE   Members m
SET      PointsEarned = 
     ( (SELECT COUNT(*) FROM EventsLog as e WHERE e.MemberID=m.MemberID AND e.EventsTypeID=2)*10 ) + 
     ( (SELECT COUNT(*) FROM EventsLog as e WHERE e.MemberID=m.MemberID AND e.EventsTypeID=3)*3 ) +
     ( (SELECT COUNT(*) FROM ChatMessages as c WHERE c.MemberID=m.MemberID)*.1 );

Test case:

CREATE TABLE Members (MemberId int, PointsEarned int);
CREATE TABLE EventsLog (MemberID int, EventsTypeID int);
CREATE TABLE ChatMessages (MemberID int);

INSERT INTO Members VALUES (1, 0);
INSERT INTO Members VALUES (2, 0);
INSERT INTO Members VALUES (3, 0);

INSERT INTO EventsLog VALUES (1, 2);
INSERT INTO EventsLog VALUES (1, 2);
INSERT INTO EventsLog VALUES (1, 3);
INSERT INTO EventsLog VALUES (2, 2);
INSERT INTO EventsLog VALUES (3, 3);

INSERT INTO ChatMessages VALUES (1);
INSERT INTO ChatMessages VALUES (1);
INSERT INTO ChatMessages VALUES (2);

Result:

SELECT * FROM Members;
+----------+--------------+
| MemberId | PointsEarned |
+----------+--------------+
|        1 |           23 |
|        2 |           10 |
|        3 |            3 |
+----------+--------------+
3 rows in set (0.00 sec)
Daniel Vassallo
Yup, looks like it's working. Thanks, you're a great help ;)
Jhourlad Estrella
@Jhourlad: And you can attach `WHERE m.MemberID = ?` to do a points calculation of just a single member.
Daniel Vassallo
Thanks for the update. I actually need this for a CRON JOB that will update the members' points based on how active they are on the site. AAMF, I am already using it now! Thanks for the help.
Jhourlad Estrella
@Jhourlad: Then the update query in the answer should do :)
Daniel Vassallo
BTW, was the answer accepted and then un-accepted by any chance? ... (I'm trying to see which of my answers got unaccepted last night)
Daniel Vassallo
Sorry about that. I re-accepted your answer.
Jhourlad Estrella