I have three tables in the database: one is users, the second one is questions, and the other is the pivot table called users_questions. The point is that a question previously asked to a user shouldn't be asked to that user any more. So ı'm inserting a row into the pivot table with the question_id and the user_id. How can I write an SQL statement to fetch such a random row from the table questions that the row's id doesn't match a question_id in the table users_questions, and the user_id of that row from the table users_questions doesn't match the currently signed-in user's id, either?
I've tried LEFT JOIN, but it fetches the previously inserted questions into the table users_questions for the currently signed-in user. The statements I've tried are below:
SELECT * FROM questions LEFT JOIN users_questions ON questions.id != users_questions.question_id AND users_questions.user_id != 'some_id' ORDER BY RAND() LIMIT 1;
SELECT * FROM questions, users_questions WHERE questions.id != users_questions.question_id AND users_questions.user_id != 'some_id' ORDER BY RAND() LIMIT 1;
Thanks.
You can do a LEFT JOIN on questions to user_question and look for the nulls
SELECT * FROM questions
LEFT JOIN users_questions ON questions.id = users_questions.question_id AND
users_questions.user_id = 'some_id'
WHERE user_questions.questions_id IS NULL
ORDER BY RAND() LIMIT 1
Check that gives the right list before putting the ORDER BY RAND() and LIMIT in.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.