mysql 按多次出现排序

mysql order by multiple occurence

我真的不知道该给这个问题起什么标题,所以这是我最好的猜测。

这是我的问题。我有一个看起来像这样的 table:

Structure
__________________
problemID | actualDifficulty | personID | userDifficulty

Rows
__________________
39414 | 5 | 100001| 1
39414 | 5 | 100000| 1
39411 | 5 | 100000| 3
39411 | 5 | 100001| 3
39416 | 4 | 100001| 4
39413 | 3 | 100001| 3
39415 | 1 | 100001| 1
39412 | 1 | 100001| 1
39412 | 1 | 100000| 1

所以有一堆不同的 "problems" 有一定的难度,从 1 容易到 5 难。上面的table是每个用户在做题,说自己解决题的难度。

我想要的是获得一个 "top 50" 列表,它将根据一些事情对每个人进行排名。

明白了吗?有点?

这是我目前的情况

SELECT COUNT( * ) , personID
FROM table
WHERE actualDifficulty =5
GROUP BY personID
ORDER BY userDifficulty ASC
LIMIT 0 , 50

有什么帮助吗?

应该对表使用动态 select 你可以获得通用解决方案

  select t1.personID, t1.actualDifficulty, t1.count_ad, t2.userDifficulty
  from  (
    select personID, actualDifficulty, count(* ) as count_ad
    from my_table
    group by actualDifficulty
  ) t1
  left join (
    select  distinct personID, userDifficulty
    from my_table
  ) t2 on t1.personID = t2.personID
  order by t1.actualDifficulty, t1.count_ad, t2.userDifficulty

这将根据您的用户解决的最难问题对他们进行排名。我提出它不是因为它回答了你的问题,而是因为它很简单。

  SELECT COUNT(*) num, 
         MAX(actualDifficulty) actuaDifficulty, 
         MAX(userDifficulty) userDifficulty, 
         personID
    FROM probs
GROUP BY personID
ORDER BY 2 DESC, 3 DESC, 1 DESC
   LIMIT 0 , 50

(请注意,我在 ORDER BY 子句中使用列序号来简化事情。)

这是您问题的实际答案。这取决于 MySQL 小道消息,如果表达式 actualDifficulty = 5 为真,则其值为 1,否则为 0。所以有一个不错的小 SUM(actualDifficulty = 5) hack 可能。 (http://sqlfiddle.com/#!9/57612b/1/0)

SELECT COUNT(*) num, 
       SUM(actualDifficulty = 5) actual5,  /* count of actualDiff = 5 */
       SUM(userDifficulty = 5) user5,      /* count of userDiff = 5 */
       SUM(actualDifficulty = 4) actual4,  /* count of actualDiff = 4 */
       SUM(userDifficulty = 4) user4,      /* count of userDiff = 4 */
       SUM(actualDifficulty = 3) actual3,  /* etc.... */
       SUM(userDifficulty = 3) user3,
       SUM(actualDifficulty = 2) actual2,
       SUM(userDifficulty = 2) user2,
       SUM(actualDifficulty = 1) actual1,
       SUM(userDifficulty = 1) user1,
       MAX(actualDifficulty) MaxActuaDifficulty, 
       MAX(userDifficulty) MaxUserDifficulty, 
       personID
  FROM probs
  GROUP BY personID
  ORDER BY 2 DESC, 3 DESC, 4 DESC, 5 DESC, 6 DESC, 
           7 DESC, 8 DESC, 9 DESC, 10 DESC, 11 DESC
LIMIT 0 , 50

您的说明说您想根据人们解决的难度为 5 的问题的数量对他们进行排名。SUM(actualDifficulty = 5) 计算得出。它是结果集中的第二列,因此 ORDER BY 2 DESC 根据该列对用户进行排名。

您接着说,如果两个用户解决了相同数量的难度为5的问题,您应该将用户难度较高的问题排名(我想这就是您的意思)。所以下一个子句就是这样排序的。

难度4、3、2、1依此类推