Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Gibt eine Liste aller Benutzer zurück, gepaart mit ihrem beliebtesten Follower. Je mehr Follower jemand hat, desto beliebter ist er

Sie können die folgende Abfrage verwenden:

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;  

Ausgabe:

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

Die Abfrage verwendet Variablen, um den größten Datensatz pro Gruppe zu erhalten.

Demo hier