sql >> Database >  >> RDS >> Mysql

Grootste N-records selecteren in X-groepen

SELECT catX.category
       catX.interest
       t1.user_id
       t1.score
FROM 
    ( SELECT category 
           , interest 
      FROM tableX 
      WHERE user_id = @user_id_we_are_interested_in     --- specific user 
      ORDER BY interest DESC
      LIMIT @X                         --- top @X categories per specific user 
    ) AS catX 
  JOIN 
    tableX AS t1 
      ON t1.category = catX.category 
  LEFT JOIN 
    tableX AS t2 
      ON  t2.category = t1.category 
      AND t2.score > t1.score 
  GROUP BY t1.category
         , t1.user_id
  HAVING COUNT(t2.score) < @N                      --- top @N users per category 
  ORDER BY catX.interest DESC 
         , t1.score DESC 


  1. Een probleem hebben om mysqli_query uit te voeren

  2. Gegevens ophalen uit opgeslagen procedure met meerdere resultaatsets

  3. Heeft de samengestelde index richting in MySQL?

  4. Coderingsprobleem in AJAX