[英]how to copy the selected row in datatable to another table in database mysql
[英]MySQL - How to select row were not selected in another table
我正在使用php和mysql創建多項選擇測驗Web應用程序; 每個測驗10個問題。 每次它將從數據庫中隨機選擇10個問題,並將那些選擇的qid插入到結果表中。
目前,我有兩個表; 用於問題和選項的questions
表,以及用於存儲選定問題的results
表。
我的問題是如何選擇結果表中不存在的問題? 我的數據庫中有100個問題,如果用戶遇到last(100)問題該怎么辦。
questions
表:
+-------+---------------+----------------+
| qids | q_text | q_options |
+-------+---------------+----------------+
| 1 | example1 |opt1, opt2, opt3|
| 2 | example2 |opt1, opt2, opt3|
| 3 | example3 |opt1, opt2, opt3|
+-------+---------------+----------------+
results
表:
+----+------------------------------+
| id | qids |
+----+------------------------------+
| 1 | 1,2,3,4,5,6,7,8,9,10 |
| 2 |11,12,13,14,15,16,17,18,19,20 |
+----+------------------------------+
結果表的結構不適用於此目的。 您可能想在結果和問題之間使用hasMany關系。
您需要將每個問題存儲在單獨的行中。 為此,我展示了第三個表(result_questions),該表將結果與hasMany關系中的問題相關聯。 也就是說:每個結果行都有很多問題。
問題表:
qids, q_text, q_options
結果表:
id, anyothercolumn
result_questions表:
id, resultid, qid
在result_questions表中,id是自動增加的,resultid是結果表中的外鍵,qid是問題表中的外鍵。
最后,我們將得到一個如下表:
result_questions:
+----+----------+-----+
| id | resultid | qid |
+----+----------+-----+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
| 4 | 1 | 4 |
| 5 | 1 | 5 |
| 6 | 1 | 6 |
| 7 | 1 | 7 |
| 8 | 1 | 8 |
| 9 | 1 | 9 |
| 10 | 1 | 10 |
| 11 | 2 | 11 |
| 12 | 2 | 12 |
| 13 | 2 | 13 |
| 14 | 2 | 14 |
| 15 | 2 | 15 |
| 16 | 2 | 16 |
| 17 | 2 | 17 |
| 18 | 2 | 18 |
| 19 | 2 | 19 |
| 20 | 2 | 20 |
+----+----------+-----+
注意:如果隨機選擇問題,則上面的qid的順序將是隨機的,而不是順序的。
然后,您可以使用查詢:
SELECT * FROM questions
WHERE id NOT IN (SELECT qid FROM result_questions)
ORDER BY RAND() LIMIT 10;
那會給您未曾問過的問題。 創建新的結果行后,您希望將它們存儲到result_questions表中,因此不會再被詢問。
另外,您可能想重構選項的存儲方式。 如果您知道最大數量的選項,則對每個選項使用單獨的列,或者對選項的問題也使用hasMany關系
希望您能理解這些內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.