简体   繁体   中英

construct Mysql Query

Suppose I have a table called tblSchoolSupplies that looks like this:

itemsID categoryID subCategoryID itemName
1          1           1          pencil
2          1           1          eraser
3          2           2          toilet paper
4          1           2          bond paper
5          1           3          bag
6          1           1          ruler
7          1           2          compass
8          1           3          pencil case
9          2           2          soap

What I want to do is construct a query that meets these 4 criteria:

1) select rows under categoryID = 1
2) group rows by subCategoryID
3) limit 2 rows per subCategoryID
4) rows must be selected by random

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM