0

I have a MySQL table which is called Questions.

Rows in this table have one of their fields called category_name and I currently have 5 different category names

My question is:

How can I select 2 random rows from each category, and return them as an array?

Obviously I need 10 questions returned back but the way I have it now it might select unequal number of questions between the categories.

Here is my function this far which selects all questions at the moment:

  function populateQuestions(){

        global $dbc;
         $query = "SELECT * FROM Questions";

         $result = $dbc->getAll($query);
         shuffle($result);

         return $result;  
    }

My category_names are:

  • Meat
  • Vegetables
  • Fish
  • Exotic
  • Local

My tables are quite small and the game is not really speed-oriented so I prefer keeping all the questions in one table as they are now.

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
  • Use the solutions in http://stackoverflow.com/questions/3140589/mysql-query-select-top-3-rows-from-table-for-each-category?rq=1 and use `ORDER BY cagtegory_name, RAND()` – Barmar Jul 03 '14 at 07:06
  • duplicate of [http://stackoverflow.com/questions/5633619/select-2-products-from-each-category-in-mysql](http://stackoverflow.com/questions/5633619/select-2-products-from-each-category-in-mysql) – michikot Jul 03 '14 at 07:06

0 Answers0