MySQL Query - Sum the Capacity of Multiple Warehouses

妖精的绣舞 提交于 2019-12-12 05:02:45

问题


We have a MySQL database that has two tables, Warehouse and Crate

Warehouse:
WarehouseID (primary key)
Location (varchar)

Crate:
CrateID (primary key)
Warehouse (foreign key to a Warehouse record)
Max_Capacity (int) (the amount of boxes that can be packed into a crate)

I would like to write a query that returns a sum of all the crates' max_capacity for each Warehouse. I'm having trouble with duplicate entries and inner joins, so what I'm hoping for is something like:

LOCATION:    WAREHOUSE_ID:  TOTAL_CAPACITY:
Shoreline    1              60
Bellevue     2              120
Ballard      3              200

Each warehouse might have 10 or so crates.


回答1:


just group by the warehouses:

(assuming the foreign key in the crate table is called warehouseID)

SELECT 
  warehouse.location, 
  warehouse.warehouseID, 
  SUM(crate.max_capacity) AS total_capacity
FROM warehouse
INNER JOIN crate
  ON crate.warehouseID = warehouse.warehouseID
GROUP BY
  warehouse.warehouseID



回答2:


select w.location, w.warehouse_id, sum(c.capacity) as total_capacity 
from warehouse w, crate c 
where w.warehouse_id = c.warehouse_id 
group by c.warehouse_id



回答3:


You should look up the mysql manual for these words:

  • inner join
  • group by
  • sum()

These can help you assembly the query you want.



来源:https://stackoverflow.com/questions/8105654/mysql-query-sum-the-capacity-of-multiple-warehouses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!