我有一个看起来像这样的表:
有100个问题。
Table Structure for "Questions Table":
title:
answerA:
answerB:
answerC:
answerD:
category:
difficulty:
每个问题可以有5个类别中的一个(" 1,2,3,4或5")和3个难度级别中的1个("简单,中等或难度" )。
目前我按类别对其进行排序,并随机分组:
"SELECT * FROM Questions order by category, rand()";
所以现在问题按类别排序并随机化。
我希望每个类别的结果都有不同的难度级别。
这样的事情:
question 1 , category 1, difficulty easy
question 3 , category 1, difficulty medium
question 4 , category 1, difficulty hard
question 2 , category 1, difficulty easy
question 5 , category 2, difficulty easy
question 6 , category 2, difficulty medium
question 7 , category 2, difficulty hard
question 2 , category 2, difficulty easy
question 8 , category 3, difficulty easy
question 10, category 3, difficulty medium
question 9 , category 3, difficulty hard
question 0 , category 3, difficulty easy
等等。
我如何复制上述内容? 我的排序似乎需要2个标准,每次为新类别打印问题时,难度标准都需要更改。
我发现的大多数Google搜索结果都与按2个字段进行分类但订单相同。
答案 0 :(得分:1)
好。所以对于这样的订单,我们首先需要grouped rank:
(SELECT title, category, difficulty,
@rank:=CASE
WHEN @category <> category OR @difficulty <> difficulty
THEN 0
ELSE @rank+1 E
ND AS rn,
@difficulty = difficulty,
@category = category
FROM
(SELECT @rank:= -1) s,
(SELECT @category:= -1) c,
(SELECT @difficulty:= -1) d,
(SELECT *
FROM questions
ORDER BY category, difficulty, rand()
) t) as q
这为我们创建了一个表格,其中每个问题都有它在类别中的排名。现在让我们对它进行排序:
SELECT *
FROM (...) as q
ORDER BY category, rn, CASE
WHEN difficulty = 'easy'
THEN 1
WHEN difficulty = 'medium'
THEN 2
ELSE 3
END;