MySQL:根据table2中标记为table1的值从table3中检索结果

时间:2013-04-30 12:43:46

标签: mysql

表5:经理

id | name
1 | Steve
2 | Jacob

table4:deputy_managers

id | manager_id | name
1 | 2 | Mary
2 | 2 | Linda
3 | 1 | Nathan

table3:team_leads

id | deputy_manager_id | name
1 | 3 | Stephen
2 | 1 | Patrick
3 | 2 | Tony
4 | 1 | Austin

table2:sales_executives

id | team_lead_id | name
1 | 1 | Johnny
2 | 3 | Dalton
3 | 4 | Sonora
4 | 2 | Jessie

table1:sales

id | sales_executive_id | product | quantity
1 | 3 | product1 | 10
2 | 2 | product3 | 6
3 | 3 | product2 | 5
4 | 1 | product1 | 4

使用sales表中的数据,我想编写mysql查询来获取所售产品的总数量:

  1. 来自经理Steve的团队。
  2. 来自副经理Mary的团队。
  3. 来自团队领导Tony的团队。
  4. 请帮忙。

    提前致谢。

1 个答案:

答案 0 :(得分:0)

  1. 来自经理史蒂夫的团队

    SELECT   product, SUM(quantity)
    FROM     managers         m
        JOIN deputy_managers  d ON d.manager_id         = m.id
        JOIN team_leads       t ON t.deputy_manager_id  = d.id
        JOIN sales_executives e ON e.team_lead_id       = t.id
        JOIN sales            s ON s.sales_executive_id = e.id
    WHERE    m.name = 'Steve'
    GROUP BY product
    
  2. 来自副经理玛丽的团队

    SELECT   product, SUM(quantity)
    FROM     deputy_managers  d
        JOIN team_leads       t ON t.deputy_manager_id  = d.id
        JOIN sales_executives e ON e.team_lead_id       = t.id
        JOIN sales            s ON s.sales_executive_id = e.id
    WHERE    d.name = 'Mary'
    GROUP BY product
    
  3. 来自团队领导Tony的团队

    SELECT   product, SUM(quantity)
    FROM     team_leads       t
        JOIN sales_executives e ON e.team_lead_id       = t.id
        JOIN sales            s ON s.sales_executive_id = e.id
    WHERE    t.name = 'Tony'
    GROUP BY product
    
  4. sqlfiddle上查看。