Here, the chapter_id can be two or more than two. I need to query in a way that every chapter give the output of equal no. of questions.
i.e. If the total question is 50, and from 5 chapters, then each chapter should give 10 questions.
SELECT id, chapter_id, question, answer FROM `questions`
WHERE `chapter_id` IN (19, 20, 21, 22, 23)
ORDER BY `chapter_id`
I tried it by quering separate queries. i.e. first check the number of chapters and loop it through an array.
<?php
$total_qsn = 50;
$chap[] = {19, 20, 21, 22, 23};
$avg = $total_qsn/count($chap);
for($i=0, $i<count($chap); i++){
$sql = "SELECT id, chapter_id, question, answer FROM `questions` WHERE chapter_id = {$chap[i]} LIMIT 0, {$avg}";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
// Print the array members
}
}
?>
Isn't there any way, that, I can do the whole thing by a single query only! Thank you! Any Idea please!
Equality operators When used in a query, these can be used to select individual records. For example: SELECT FirstName, LastName FROM Customer WHERE CustomerID = 13; Or we can use them to retrieve records that meet a specified criteria.
Queries retrieve rows and columns from tables. After you run a query, you can further limit the number of items shown in the datasheet by applying filters. Filters are a good choice when you want to temporarily limit the query results without going into Design View to edit your query.
The WHERE clause is used to filter records. It is used to extract only those records that fulfill a specified condition.
The WHERE clause is used to filter results by specifying a filter condition or selection criteria. Usage is not limited to just SELECT queries, as this clause is also used with the UPDATE and DELETE DML commands.
Try this:
SELECT id, chapter_id, question, answer
FROM (SELECT IF(@chapterId=@chapterId:=chapter_id, @id:=@id+1, @id:=0) queNo, id, chapter_id, question, answer
FROM `questions`, (SELECT @chapterId:=0, @id:=0) AS A
WHERE `chapter_id` IN (19, 20, 21, 22, 23)
ORDER BY `chapter_id`
) AS A
WHERE queNo < 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With