来自其他表的MySQL查询总数

时间:2018-08-05 19:06:43

标签: mysql

表jenis_usaha

ID JENIS_USAHA  
1 Laundry  
2 Restauran

表waralaba

ID ID_JENIS_USAHA  
1 1  
2 2

表perusahaan

ID NAME ID_WARALABA  
1 A 1  
2 B 2  
3 C 1
4 D 1

桌子插座

ID ID_PERUSAHAAN  
1 1  
2 1  
3 2  
4 2  
5 1  
6 1  
7 1  
8 1  
9 1

我想要的结果是这样的

ID JENIS_USAHA TOTAL_PERUSAHAAN TOTAL_OUTLET  
1  Laundry          3                7   
2  Restauran        1                2

我有这个mysql查询

SELECT  ju.ID, 
        ju.JENIS_USAHA,
        COUNT(p.ID) AS TOTAL_PEMBERI,
                (SELECT count(o.ID)
                    FROM outlet o 
                    WHERE p.ID = o.ID_PERUSAHAAN
                        AND w.ID = p.ID_WARALABA
                        AND ju.ID = w.ID_JENIS_USAHA
                    ) AS TOTAL_OUTLET
FROM jenis_usaha ju
            LEFT JOIN waralaba w ON w.ID_JENIS_USAHA = ju.ID
            LEFT JOIN perusahaan p ON p.ID_WARALABA = w.ID           
GROUP BY ju.ID  

我没有错误,但是TOTAL_OUTLET的结果是错误的。您能告诉我正确的查询吗?谢谢

2 个答案:

答案 0 :(得分:0)

我花了很长时间才能理解您的查询,所以我决定自己做。 无论如何,这带来了您想要的结果。请检查是否适合您的情况。 =)

顺便说一句,st代表小计

SELECT 
    st.id,
    st.name,
    count(ps_id) AS ps_amount,
    sum(ol_amount) AS ol_amount
FROM 
    (SELECT
        ju.id,
        ju.name,
        ps.id AS ps_id,
        count(ol.id) as ol_amount
    FROM
        jenis_usaha ju
    INNER JOIN
        waralaba wl 
        ON wl.id_jenis_usaha = ju.id
    LEFT JOIN
        perusahaan ps
        ON ps.id_waralaba = wl.id
    LEFT JOIN
        outlet AS ol
        ON ol.id_perusahaan = ps.id
        GROUP BY 
            ju.id,
            ju.name,
            ps.id) st
GROUP BY
    st.id,
    st.name

答案 1 :(得分:0)

您输入的连接错误,这就是输出错误的原因 下面的查询应该按您的方式工作

  select j.id ,j.name,TOTAL_PERUSAHAAN,outlet as TOTAL_OUTLET 
  from  jenis_usaha j inner join         
    (select p.id,count(o.ID_PERUSAHAAN) as outlet from outlet o
    inner join perusahaan p
    on o.ID_PERUSAHAAN=p.id
    group by p.id
    ) t1 
    on t1.id=j.id
    inner join 
    (        
    select w.id, count(p.ID_WARALABA) as TOTAL_PERUSAHAAN  
    from  waralaba w inner join perusahaan p
    on w.id=p.ID_WARALABA
    group by w.id
      ) t2
      on t2.id=j.id


id  name    TOTAL_PERUSAHAAN    TOTAL_OUTLET
1   Laundry     3                   7
2   Restauran   1                   2

这是小提琴链接,您可以在其中找到详细信息

http://sqlfiddle.com/#!9/400c971/6