sql >> Base de Datos >  >> RDS >> Mysql

Devuelve una lista de todos los usuarios, junto con su seguidor más popular. Cuantos más seguidores tiene alguien, más popular es

Puede utilizar la siguiente consulta:

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;  

Salida:

person_name follower_name   cnt
--------------------------------
John        Rohn            3
Veronica    Rohn            3
Ali         John            2
Rohn        Ali             2

La consulta utiliza variables para obtener el mayor registro por grupo.

Demostración aquí