根據您目前的模式,你可以嘗試使用一個查詢這樣
SELECT r.question, r.answer, q.answer wrong_answer
FROM
(
SELECT question, answer
FROM questions
ORDER BY RAND()
LIMIT 1
) r JOIN questions q
ON q.question <> r.question
ORDER BY RAND()
LIMIT 4;
輸出示例:
| QUESTION | ANSWER | WRONG_ANSWER |
|-----------|---------|--------------|
| question4 | answer4 | answer9 |
| question4 | answer4 | answer11 |
| question4 | answer4 | answer7 |
這裏是SQLFiddle演示
很明顯,你看問題和權利回答呃一次(例如從第一行開始),並從wrong_answer
列中獲取其他3個錯誤答案,同時在php中遍歷結果集。
,或者你還可以去收拾錯誤的答案在分隔列表
SELECT question, answer, GROUP_CONCAT(wrong_answer) wrong_answer
FROM
(
SELECT r.question, r.answer, q.answer wrong_answer
FROM
(
SELECT question, answer
FROM questions
ORDER BY RAND()
LIMIT 1
) r JOIN questions q
ON q.question <> r.question
ORDER BY RAND()
LIMIT 3
) q
輸出示例:
| QUESTION | ANSWER | WRONG_ANSWER |
|-----------|---------|-------------------------|
| question9 | answer9 | answer6,answer1,answer7 |
這裏是SQLFiddle演示
然後在PHP你總是有單行結果集。你可以很容易地explode()
wrong_answer
值。
請顯示您的表架構和示例數據。看起來規範化是有序的。 – peterm
你只是想隨機化問題,然後拿走它們並在第二個查詢中搜索該問題的答案吧? –
是的,這就是我正在做的事情,但我希望將答案打印在隨機的位置上,並附帶3張我的表格的隨機答案。問題表: question_ID,question,answer,lesson_FK –