Anne Schwarz Anne Schwarz - 6 days ago 8
MySQL Question

sql count unique values from specific field

|from| to |
| 7 | 9 |
| 7 | 9 |
| 3 | 9 |
| 3 | 2 |


Lets say I'm user 9 and want to find out how many user have wrote to me.
With the query:

SELECT COUNT(*) FROM tab WHERE to = 9;


I get 3 which means I got 3 new messages, but how to find out ho many users wrote me which would be 2 in this case?

Answer

You want count(distinct):

SELECT COUNT(DISTINCT `from`)
FROM tab
WHERE `to` = 9;
Comments