I have a table called “users” which has info(first name,etc…) with the following rows:
username
----------
mikha
guy
maricela
Another table called “questions” with the following rows:
asker
----------
mikha
mikha
maricela
guy
maricela
Another table called connections with the following rows:
username1
----------
guy
mikha
mikha
I want to select info about the user ‘mikha’ including count when he is questions.asker and when he is connections.username1. I use the following query:
SELECT COUNT(questions.asker) AS asking,COUNT(connections.username1) AS following
FROM users LEFT JOIN questions ON users.username = questions.asker
LEFT JOIN connections ON users.username = connections.username1
WHERE users.username = 'mikha'
Expected results:
asking: 2 (as mikha is found 2 times asking)
following: 2 (as mikha is found 2 times following)
Actual results:
asking: 4
following: 4
If I use COUNT(DISTINCT questions.asker) and COUNT(DISTINCT connections.username1) I get the result always as 1 as it counts the name only once. I tried GROUP BY also with no avail.
So, how can I use distinct to avoid duplicates and the same time count the same name all the times available not just one?
I created this fiddle to test the problem yourself.
Thanks in advance
Regards
Michael
Do you have an ID in questions table, and one ID in connections table? If you have, you could use this:
EDIT: based on your comments, i think that what you need is this:
the only problem here is that counting by
CONCAT(...)does not take advantage of indexes and can be slow. And also it could happen thatCONCAT(userA, userB) = CONCAT(userC, userD)even ifuserA<>userC and userB<>userD. You could useCONCAT(username1, ':', username2)to avoid this, but only if you make sure that no username contains:character. But if it is possible, i would suggest you to add anidalso to your connections table.