簡體   English   中英

從每個類別獲取隨機數據,每個類別具有不同的限制php-mysql

[英]Get random data from each category with different limit for each category php-mysql

我有一個具有idtypequestionoption1 .. 4answer字段的問題表。 有三種類型的問題A,B和C。

對於A型和B型,我必須隨機抽取7個問題,對C型則必須隨機抽取6個問題。每個測試總共顯示20個問題。

我必須一次只顯示一個問題,然后在下一個按鈕上顯示下一個。 所以我為此使用分頁。 因此,我必須在mysql查詢的末尾添加$limit$start 我如何為此編寫一個查詢。

我寫了兩個查詢,例如:

1:
(select * from dgm_questions Where ques_type IN('A') Order by rand() ASC Limit 7) union (select * from dgm_questions Where ques_type
IN('B') Order by rand() ASC Limit 7) union (select * from
dgm_questions Where ques_type IN('C') Order by rand() ASC
Limit 6)

2: select ques_id, ques_type from dgm_questions Where ques_type IN('A','B','C') Order by rand() ASC Limit 20

第一個查詢總共給我20個問題,但無法添加$limit ,為分頁添加$limit $start ,第二個查詢未顯示A的限制7,B類型的限制為C類型的限制6。

如何為此編寫查詢?

我想使用會話解決方案(如果可以的話),因為您不想為每個請求選擇20個隨機問題(當您單擊下一個按鈕時),所以我猜想,如果您使用分頁,則會發生這種情況。

因此,我的建議是根據您的條件獲取20個隨機問題,並將它們(實際上只是ID)存儲在會話中,然后從那里為每個問題頁面加載:

// on the questionaire start
// depending on wich library you use fetch the random question ids
// with your sql statement
SELECT ques_id FROM dgm_questions WHERE ques_type IN('A') ORDER BY rand() ASC Limit 7
UNION
SELECT ques_id FROM dgm_questions WHERE ques_type IN('B') ORDER BY rand() ASC Limit 7
UNION
SELECT ques_id FROM dgm_questions WHERE ques_type IN('C') ORDER BY rand() ASC Limit 6

// assuming the result is stored in $question_ids
// you can shuffle those questions, so they're not in type order anymore
shuffle($question_ids)

// save question ids in session
$_SESSION['question_ids'] = $question_ids;
$_SESSION['current_question_index'] = 0;

// on each request
"SELECT * FROM dgm_questions WHERE ques_id = " . $_SESSION['question_ids'][$_SESSION['current_question_index']];
$_SESSION['current_question_index']++;

現在,這僅僅是為了讓您對如何解決問題有一個整體的了解。 請記住,如果您通過random()進行排序,MySQL總是會在選擇記錄之前對整個表進行排序,這些記錄可能會破壞大型表的性能。 如果這是一個問題,那么還有其他解決方案

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM