Tobias Baumeister
Tobias Baumeister

Reputation: 2147

Mysql COUNT VS num rows performance

I want to select the amount of forum posts compared to a list of users. So it will look like this:
USERID --- FORUMPOSTS
3647 - 2
7467 - 14
2673 - 39
3224 - 5
... and so on

Now I'm asking if it would be faster to count the forum post via COUNT(*) or looping through the userlist before and creating a new query for each user to count his/her forum posts via mysql_num_rows.

Upvotes: 0

Views: 352

Answers (2)

juergen d
juergen d

Reputation: 204766

You can let SQL do the grouping and counting

select userid, count(*) as forumposts
from your_table
group by userid

Upvotes: 1

eggyal
eggyal

Reputation: 125865

Now I'm asking if it would be faster to count the forum post via COUNT(*) or looping through the userlist before and creating a new query for each user to count his/her forum posts via mysql_num_rows.

It'll be faster to do the former, "count the forum post via COUNT(*)". You can group the results as follows:

SELECT userid, COUNT(*) FROM my_table GROUP BY userid

It'll be even faster still if your table has an index on the userid column.

Upvotes: 0

Related Questions