sql >> Database teknologi >  >> RDS >> Mysql

forespørgsel efter brugerens rangering i en-til-mange tabeller

SELECT u.id,total_score,
 ( SELECT COUNT(*) FROM
    (SELECT u1.id, (IFNULL(u1.freebee,0)+ IFNULL(SUM(score),0)) as total_score
     FROM users u1
     LEFT JOIN games g ON (g.userId = u1.id)
     GROUP BY u1.id
    )x1
   WHERE x1.total_score > x.total_score
 )+1 as rank,

( SELECT COUNT(DISTINCT total_score) FROM
    (SELECT u1.id, (IFNULL(u1.freebee,0)+ IFNULL(SUM(score),0)) as total_score
     FROM users u1
     LEFT JOIN games g ON (g.userId_Id = u1.id)
     GROUP BY u1.id
    )x1
   WHERE x1.total_score > x.total_score
 )+1 as dns_rank

 FROM users u

 LEFT JOIN
  ( SELECT u1.id, (IFNULL(u1.freebee,0)+ IFNULL(SUM(score),0)) as total_score
    FROM users u1
    LEFT JOIN games g ON (g.userId = u1.id)
    GROUP BY u1.id
  )x ON (x.id = u.id)

rank - (normal rang - f.eks. - 1,2,2,4,5), dns_rank - tæt rang (1,2,2,3,4). Kolonne total_score - kun til fejlretning...



  1. Under import af mysqldump-fil ERROR 1064 (42000) nær ' ■/ ' på linje 1

  2. Forkert decimalværdi (heltal):' ' mySQL

  3. INSERT INTO ... FRA SELECT ... RETURNERER id-tilknytninger

  4. Enhedstest for PL/SQL