Mark
Mark

Reputation: 647

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.

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.

Upvotes: 1

Views: 71

Answers (2)

FuzzyTree
FuzzyTree

Reputation: 32392

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

Upvotes: 1

Strawberry
Strawberry

Reputation: 33945

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

Upvotes: 0

Related Questions