SQL MariaDB Count Query 3 Tables Per type

SQL MariaDB Count Query 3 Tables Per type

我有 4 张桌子。我正在尝试计算每个站点的 infoType 总数。如果网站没有 infoType,那么它仍然 returns 因为找到 0

站点

 |ID|siteName|
 |1 |Orlando |
 |2 |Tampa   |

系统

 |ID|siteID|systemName|
 |1 |1     |orlCust1  |
 |2 |1     |orlCust2  |
 |3 |2     |tamCust1  |
 |4 |2     |tamCust2  |

信息类型

|ID|infoType|infoName|
|1 |1       |RED     |
|2 |15      |BLU     |
|3 |30      |ORG     |
|4 |45      |YLW     |

找到订单

|ID|systemID|infoType|infoName                 |
|1 |1       |1       |Alert - Found Record     |
|2 |3       |15      |Informational            |
|3 |4       |1       |Alert - Found Record     |
|4 |3       |30      |Informational            |
|5 |1       |1       |Alert - Found Record     |
|6 |2       |15      |Informational            |
|8 |1       |1       |Alert - Found Record     |
|9 |3       |45      |Informational            |

我正在寻找这样的结果

 siteName|infoType|foundOrders
 ORLANDO |RED     |3
 ORLANDO |BLU     |1
 ORLANDO |ORG     |0
 ORLANDO |YLW     |0

我想这就是你想要的:

select 
    s.siteName
  , i.infoname
  , coalesce(count(fo.ID),0) as foundOrders
from sites s
  inner join systems y
    on s.ID = y.siteID
  cross join infoType i
  left join foundOrder fo
    on fo.systemID = y.ID
   and fo.infoType = i.infoType
where s.siteName = 'Orlando'
group by 
    s.siteName
  , i.infoname
order by count(fo.ID) desc