I am using the MySQL COUNT() method to find out how many rows in two tables have the uid of u.id.
To do so, I am using the method below:
SELECT u.id, u.first_name, u.last_name, u.email, u.username, COUNT( q.uid ) AS `q_count`, COUNT( a.uid ) AS `a_count`
FROM `users` AS u
INNER JOIN `questions` AS q ON u.id = q.uid
INNER JOIN `answers` AS a ON u.id = a.uid
WHERE u.username = 'admin'
However, when I run the above query, the second count returns the same number of rows as the number of rows for the first count. I know this as the first count is returning two and the second is also doing the same, when there are two rows in the questions table and one row in the answers table.
Please can you tell me where I am going wrong?
Thanks
A sample of what I am receiving: http://d.pr/i/vcnJ
Sample data from answers: http://d.pr/i/TMkU
Sample data from questions: http://d.pr/i/tuwU
I believe the reason is that you’re doing a JOIN, which will JOIN the results together into one. Do use the same query but with
SELECT *instead and you will see why this happens.Try this: