简体   繁体   English

仅使用一个查询的带有计数器的MySQL Top10列表

[英]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. 我实际上正在处理Top10邀请列表,显示邀请了大多数其他用户的用户。

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 Invitation_by列中的数字(默认= 0)等于邀请此人的user_id

So my Top 10 Page would display: 因此,我的前10页将显示:

TOP INVITERS: 热门邀请:

  1. Julia (4 invites) 朱莉娅(4邀请)
  2. John (3 invites) 约翰(3邀请)
  3. Natasha (2 invites) 娜塔莎(2邀请)

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? 我现在的问题是,我能否仅使用一个包含总邀请计数器的mysql查询,最终使用子查询来实现这一点,如果可以,该查询必须如何?

$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? 出于性能原因,具有这种表格样式和数百万个用户,是否有可能挑选出尚未邀请某人的人,也许以前进行过in_array检查?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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