Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need a MySQL query that can filter the results

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!

like image 688
TheManish Avatar asked Dec 24 '13 07:12

TheManish


People also ask

How do I filter query results in SQL?

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.

Can filters be used on query results?

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.

Which query is used to filter records in SQL?

The WHERE clause is used to filter records. It is used to extract only those records that fulfill a specified condition.

Which statement is used to filter data in MySQL?

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.


1 Answers

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
like image 135
Saharsh Shah Avatar answered Oct 11 '22 16:10

Saharsh Shah