简体   繁体   中英

Count row number based on a value of other column

I've a MySQL table like that

+----+------+--------+
| id | name | ref_by |
+----+------+--------+
| 1  | SM   |        |
+----+------+--------+
| 2  | MO   | 1      |
+----+------+--------+
| 3  | Go   | 2      |
+----+------+--------+
| 4  | ZZ   | 1      |
+----+------+--------+

It is a user table where the "ref_by" column holds the id of the user by whom the user is referred.

I want to select the top 10 user who have top referral. I did that on PHP by searching the user id and counting the referred user. That is too much time consuming.

What will be an efficient query that will produce a result like this:

name ref_count
SM   2
MO   1

We can try using a self-join here:

SELECT
    t1.name,
    COUNT(t2.id) AS ref_count
FROM yourTable t1
LEFT JOIN yourTable t2
    ON t1.id = t2.ref_by
GROUP BY
    t1.name
ORDER BY
    ref_count DESC
LIMIT 10;

在此处输入图片说明

Demo

Note: If you don't want to see names which had a zero referral count, then add the following HAVING clause to the above query:

HAVING ref_count > 0

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM