简体   繁体   English

如何按照唯一且预定的顺序(而不是asc或desc)对来自mysql数据库的数据进行排序

[英]How do I sort data from a mysql db according to a unique and predetermined order, NOT asc or desc

I need to show 1000 test questions to a student, 10 per page. 我需要向学生展示1000个测试问题,每页10个。

The questions are in a mysql table, the answers will go in another table. 问题在mysql表中,答案将在另一个表中。

I need each students questions to appear in a different predetermined order than any other students. 我需要每个学生的问题以不同于其他任何学生的预定顺序出现。 The sort order is predetermined when they register and placed in a usermeta table. 当他们注册并放置在usermeta表中时,排序顺序是预先确定的。

In the usermeta table there is a column that lists the order in which the questions should be shown. 在usermeta表中,有一列列出了问题显示的顺序。 The order in that column is unique to each student and looks like this example: 8|14|97|54|21|37|54|61 ...etc. 该列中的顺序对于每个学生而言都是唯一的,并且类似于以下示例:8 | 14 | 97 | 54 | 21 | 37 | 54 | 61 ...等。

The first question to be shown to the student would be question #8, and then question #14, and then question #97, and so on, listing 10 per page. 向学生显示的第一个问题是第8个问题,然后是第14个问题,然后是第97个问题,依此类推,每页列出10个问题。

I don't need to sort the questions asc or desc. 我不需要按升序或降序对问题进行排序。 Also, I can change the db structure if that would help find a solution. 另外,如果可以帮助找到解决方案,我可以更改数据库结构。

Also, I can change the db structure if that would help find a solution. 另外,如果可以帮助找到解决方案,我可以更改数据库结构。

If changing the db structure is possible, then instead of storing the sorting order as a pipe separated string, store it in a separate table that maps each question to the order it should appear in for a given student. 如果可以更改数据库结构,则不要将排序顺序存储为以管道分隔的字符串,而应将其存储在单独的表中,该表将每个问题映射到给定学生应出现的顺序。 ie

student_id, sort_order, question_id
1               1               8
1               2               2
1               3               97

Then join on your sorting table when selecting your questions for a particular student. 然后在为特定学生选择问题时加入您的排序表。

SELECT q.* FROM 
questions q
JOIN questions_sorting_order qso
ON q.id = qso.question_id
ORDER BY qso.sort_order
WHERE qso.student_id = :student_id
SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+

SELECT i2.i*10+i1.i x
     , FIND_IN_SET(i2.i*10+i1.i,'8,14,97,54,21,37,54,61') y 
  FROM ints i1
     , ints i2
HAVING y > 0 
 ORDER 
    BY y;
+----+---+
| x  | y |
+----+---+
|  8 | 1 |
| 14 | 2 |
| 97 | 3 |
| 54 | 4 |
| 21 | 5 |
| 37 | 6 |
| 61 | 8 |
+----+---+

Note that 54 is ignored second time around 请注意,第二次忽略54

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM