找到最受欢迎的人的追随者。一个人的追随者越多
他们很受欢迎。
我需要SQL查询来选择最受欢迎的追随者。
我的桌子-(追随者)

id | person_id | follower_person_id
1    1            2
2    1            3
3    2            1
4    2            4
5    3            1
6    3            2
7    3            4
8    4            3

个人id 1共有2个跟随者(个人id 2,个人id 3),个人id
2有2个追随者(1号人物,4号人物),3号人物
共有3名追随者(个人id 1、个人id 2、个人id 4)和个人id
4人共有1名追随者(3人)。
因此,person_id 3是person_id 1最受欢迎的追随者,
person_id 1是person_id 2、person_id 1(或
person_id 2)是person_id 3和person_id 3最受欢迎的追随者
最受4号人物欢迎。
这是查询。。。
SELECT t1.person_id, t1.follower_person_id, t2.cnt
FROM followers AS t1
JOIN (
   SELECT person_id, COUNT(*) AS cnt
   FROM followers
   GROUP BY person_id
) AS t2  ON t1.follower_person_id = t2.person_id
WHERE t1.person_id = 1
ORDER BY t2.cnt DESC LIMIT 1

上面的查询输出是
person_id, follower_person_id, cnt
-----------------------------------
1,         3,                  3

Here is explanation of above query
此查询仅适用于查找特定人员的常用人员,但
我想找一对他们最“受欢迎”的追随者为所有人。
所以输出应该是
person_id, follower_person_id, cnt
-----------------------------------
1,         3,                  3
2,         1,                  2
3,         1,                  2
4,         3,                  3

现在我又有了一个person table
id | name
1    John
2    Ali
3    Rohn
4    Veronica

现在我想把这个id转换成人名。
最终输出应该是
person_name, follower_person_name, cnt
--------------------------------------
John,        Rohn,                 3
Ali,         John,                 2
Rohn,        John,                 2
Veronica,    Rohn,                 3

我需要sql查询来获取这些数据。

最佳答案

您可以使用以下查询:

SELECT person_name, follower_name, cnt
FROM (
   SELECT person_name, follower_name, cnt,
          @rn := IF(@pname = person_name, @rn + 1,
                    IF(@pname := person_name, 1, 1)) AS rn
   FROM (
      SELECT t3.name AS person_name, t4.name AS follower_name, t2.cnt
      FROM followers AS t1
      JOIN (
         SELECT person_id, COUNT(*) AS cnt
         FROM followers
         GROUP BY person_id
      ) AS t2  ON t1.follower_person_id = t2.person_id
      JOIN person AS t3 ON t1.person_id = t3.id
      JOIN person AS t4 ON t1.follower_person_id = t4.id
   ) AS x
   CROSS JOIN (SELECT @rn := 0, @pname := '') AS vars
   ORDER BY person_name, cnt DESC) AS v
wHERE v.rn = 1;

输出:
person_name follower_name   cnt
--------------------------------
John        Rohn            3
Veronica    Rohn            3
Ali         John            2
Rohn        Ali             2

查询使用变量以获得最大的每个组记录。
Demo here

关于mysql - 返回所有用户的列表,以及其“最受欢迎”的关注者。某人的追随者越多,他们越“受欢迎”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43285818/

10-13 00:20