简体   繁体   中英

MySQL Top10 List with counter using only one query

I am actually working on a Top10 invites list, displaying users which invited most other users.

That's the database table:

user_id  | name       | invited_by
-----------------------------------
1        | john       | 0
2        | maria      | 1
3        | johanna    | 1
4        | natasha    | 1
5        | julia      | 4
6        | antonio    | 4
7        | matthias   | 5
8        | daniel     | 5
9        | michelle   | 5
10       | anna       | 5

The number in the invited_by column (default=0) is equal to the user_id who invited this person

So my Top 10 Page would display:

TOP INVITERS:

  1. Julia (4 invites)
  2. John (3 invites)
  3. Natasha (2 invites)

And so on...

My question now is, can I realize this with only one mysql query inclusive the total invites counter, eventually with a subquery and if yes, how this query must be?

$sql = "SELECT * FROM table_users ...... LIMIT 10"

And for performance reason, with this table style and million of users, is there any chance to sort out people that not yet invited someone, perhaps with an in_array check before?

Best regards.

Group a self-join, then sort and limit the results:

SELECT   invitor.name, COUNT(*) AS invites
FROM     table_users invitor
    JOIN table_users invitee ON invitee.invited_by = invitor.user_id
GROUP BY invitor.user_id
ORDER BY invites DESC
LIMIT    10

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