MySQL database records the statistical data is less than a specified value

  The landlord was doing a site of intellectual products, the need for workers to some statistics, such as number of personnel to site statistics to import less than 30, SQL should be how to write it?
  First, look at the data structure, the site points three tables, four hierarchical relationship, Organization table storage area, city levels, Projects table storage project, Stages table storage stage; there is a worker table to store personnel. This 4 id table foreign keys are stored in the parent table.
  To find the site worker generally less than 30 steps are as follows:
  1, less than 30 people find staging site id;
  2, isolated in accordance with stage connection id corresponding to the site outside the full name;
  3, 4-level grouping sorted according to site.

  Specific SQL as follows:

SELECT
    org.NAME 区域名称,
    city.NAME 城市名称,
    pr.projectName 项目名称,
    st.stageName 分期名称,
    ws.wcount 工人数量 
FROM
    Stages st
    LEFT JOIN Projects pr ON st.projectMdid = pr.projectMdid
    LEFT JOIN Organization city ON city.mdid = pr.bizOrgMdid
    LEFT JOIN Organization org ON org.mdid = city.parentMdid
    LEFT JOIN ( SELECT w.stageMdid stageMdid, count( * ) wcount FROM worker w WHERE w.deleteflag = 0 GROUP BY w.stageMdid ) ws ON st.stageMdid = ws.stageMdid 
WHERE
    st.stageMdid IN ( SELECT w.stageMdid FROM worker w WHERE w.deleteflag = 0 GROUP BY w.stageMdid HAVING COUNT( * ) < 30 ) 
ORDER BY
    org.NAME,
    city.NAME,
    pr.projectName

  Isolated data:

 

   Of course, SQL optimization can have a place, because it is only a query about the line, there is no requirement for efficiency, so the landlord in accordance with the idea to write a running account.

Guess you like

Origin www.cnblogs.com/JohanChan/p/11776110.html