|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?
You want count(distinct)
:
SELECT COUNT(DISTINCT `from`)
FROM tab
WHERE `to` = 9;
If you want a more detailed result, you can use GROUP BY
.
This way make it possible to see how many times the from
user have sent messages to to
user.
Eg
SELECT from, to, count(*)
FROM tab
GROUP BY from, to
This will return:
|from |to |count(*) |
|------|----|---------|
|7 |9 |2 |
|3 |9 |1 |
|3 |2 |1 |
You can even insert your restriction, if you want:
SELECT from, to, count(*)
FROM tab
GROUP BY from, to
HAVING to = 9
That would result in:
|from |to |count(*) |
|------|----|---------|
|7 |9 |2 |
Just an extra way to do it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.