Doug R's comment should be taken to heart. Please always include what you have tried. The questions you have are of varying difficulty and I feel like an answer will help you and others.
Example table and queries are here: http://sqlfiddle.com/#!9/3beee/6
In order to select records with category of 1, use the query below. The WHERE
clause helps filter your records to only category 1
select * from tblSchoolSupplies where categoryID = 1;
Grouping rows by sub category requires more information. You'd generally group information to get statistics. For example, how many items are there in each subcategory or how many categories do each sub-category belong. Notice that I am selecting subCategoryID and doing GROUP BY
on it also. Other columns are statistical calculations. Most, if not all, GROUP BY
queries you will encounter will have a dimension
like subCategoryID that is grouped along with statistical functions like sum
, count
, avg
etc.
select
subCategoryID,
count(*) as items_in_subcategory,
count(distinct categoryID) as distinct_categories
from tblSchoolSupplies
group by subCategoryID;
Limiting 2 rows per subCategoryID is more challenging in comparison to your first question. The answer below is based on question 12113699
-- limit 2 rows per subCategoryID
set @number := 0;
set @subCategoryID := '';
select *
from
(
select *,
@number:=if(@subCategoryID = subCategoryID, @number + 1, 1) as rownum,
@subCategoryID:=subCategoryID as field1
from tblSchoolSupplies
order by subCategoryID, itemsID
) as subcat
where subcat.rownum < 3;
Using a random sort order and limiting only 1 record output will give you a randomly selected row. Please read through discussion in question 4329396 to gain different perspective on similar question(s).
select * from tblSchoolSupplies order by rand() limit 1;