Count

查詢以從另一個表中的不同表引用中獲取項目數

  • June 16, 2015

我有 5 張桌子

- Project(PK Project_ID), 
- Bottles (PK Bottle_ID, FK Project_ID), 
- Plastics (PK Plastic_ID, FK Project_ID), 
- Glasses (PK Glass_ID,FK Project_ID) and 
- Cups (PK Cup_ID, FK Project_ID)

如何獲得一個 SQL 查詢來返回每個項目的瓶子、塑膠、眼鏡和杯子的數量,其中一個項目有很多瓶子、塑膠、眼鏡和杯子?

這樣的事情會起作用,但不一定對所有數據庫引擎都有效:

select Project_ID,
count(distinct Bottle_ID) bottlesCount,
count(distinct Plastic_ID) plasticsCount,
count(distinct Glass_ID) glassesCount,
count(distinct Cup_ID) cupsCount
from Project
left join Bottles using (Project_ID)
left join Plastics using (Project_ID)
left join Glasses using (Project_ID)
left join Cups using (Project_ID)
group by Project_ID;

引用自:https://dba.stackexchange.com/questions/104205