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

若如初见. 提交于 2020-01-05 10:36:52

问题


I need to show 1000 test questions to a student, 10 per page.

The questions are in a mysql table, the answers will go in another table.

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.

In the usermeta table there is a column that lists the order in which the questions should be shown. The order in that column is unique to each student and looks like this example: 8|14|97|54|21|37|54|61 ...etc.

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.

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.


回答1:


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. i.e.

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



回答2:


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



来源:https://stackoverflow.com/questions/24355995/how-do-i-sort-data-from-a-mysql-db-according-to-a-unique-and-predetermined-order

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!