Tom
Tom

Reputation: 488

MySQL COUNT query return total of values in rows

I have a guestbook, with messages stored in a table. There is a 'hits' field for each message. How do I run a query that will count the total number of hits?

SELECT name, COUNT(hits) FROM guestbook_message WHERE name='".$req_user_info['username']."' GROUP BY name";

This returns the amount of messages that the user has posted, where there is a value in the 'hits' field. But not the total amount of hits.

If there are 3 messages, with 3 hits each, it should return "9 hits". But the query I posted above would return "3".

Many thanks.

Upvotes: 2

Views: 6881

Answers (2)

GordonM
GordonM

Reputation: 31730

You want SUM instead of COUNT.

Upvotes: 2

Aaron W.
Aaron W.

Reputation: 9299

I think you're after SUM

SELECT name, SUM(hits) FROM guestbook_message WHERE name='".$req_user_info['username']."' GROUP BY name";

Upvotes: 7

Related Questions