I am using PHP , MySQL for the following
I have two tables
- users
- users_messages
The table “users” stores records of all users .
id name password 1 XYZ XYZ
[Here id is actually the user_id]
The table “messages” contains messages posted by users
id user_id messages 1 1 XYZ
The “users” table contains thousands of records (>5000)
The “users_messages” contains about 100 records (will keep on varying)
I am trying to get the no of messages of all the users and show them in a table .
Currently i am trying to paginate them so i need only 20 users at one page load.
I have my query as follows
SELECT u.username as username,u.id as id, COUNT( f.user_id ) AS no_of_messages
FROM users AS u
LEFT JOIN users_messages AS f ON f.user_id = u.id
GROUP BY u.id LIMIT 20
This works , but it takes a long time … may be it scans the complete table just to get the no of messages of only 20 users .
The id column of table “users” does not start from 1 , the start is random , but it auto increments from the next record .
Try this instead: