I have no idea if this is a SQL functionality or not… In short: I want rows from a table which id can’t be found in a array/comma-seperated-list in another table. More info below:
The setup is two tables; a user-table and a questions-table. The user-table has a column called answeredQuestions, a comma-seperated list, which contains the questions-ids the user has answered.
I am trying to get 4 random questions, where each one hasn’t been answered yet.
How I get 4 random with SQL query
SELECT * FROM questions WHERE id >= RAND() * (SELECT MAX(id) FROM questions) LIMIT 4
But this will just return 4 random questions, without concidering wether or not the user has had that question before.
If I should do it in Javascript, it would look like this
var questions = [1,2,3,4,5,6,7,8,9,10,11,12];
var answeredQuestions = [3,5,9,12];
var sqlReturn = [];
for (var i=0;i<4;i++) {
var randNo = 0;
while (randNo == 0 || sqlReturn.indexOf(randNo) > -1 || answeredQuestions.indexOf(randNo) > -1) {
randNo = Math.floor((Math.random()*questions.length)+1);
}
sqlReturn[i] = randNo;
}
document.write(sqlReturn);
Don’t really like your solution. You are making things a lot harder for yourself with your underlying database design.
You have two tables, one representing users and another representing questions. What you really need is a table linking the two concepts, something like user-questions.
Suggested design:-
Suggested approach for recording answers.
Every time your user answers a question, whack a row into user-questions to signify the fact that a user has answered the question.
Under this structure, solving your specific problem, finding questions that haven’t been answered yet, becomes trivial.
I don’t play day to day with MySQL, so please feel free to correct any typos, SO’ers. The approach is sound, though.