如何在MySQL中执行复杂的计算和更新视图?

时间:2017-05-09 03:51:15

标签: mysql sql

我想计算可以使用仓库中的现有物品构建多少Car_A和Car_B
期待看到 Car_A和Car_B,我可以在下面的视图中构建最大数量。

请告知我表格设计是否错误或其他。

我做了什么:我每天使用的是导出到Excel并在Excel中手动计算。

enter image description here

1 个答案:

答案 0 :(得分:1)

首先,我建议您将汽车和工具拆分到仓库中。 您可以创建另一个列并为其添加一些符号,例如C = Car和T = Tools 或者你可以创建另一张桌子并将你的车放入其中我更喜欢这种方式,我的答案就是这样,这是mydata测试

CREATE TABLE [dbo].[Assembly](
    [id_item] [int] NULL,
    [name] [varchar](100) NULL,
    [quantity] [int] NULL
) 
insert into [Assembly]
select 1,'Car_A',0
union all
select 2,'Car_B',0

CREATE TABLE [dbo].[Warehouse](
    [id_item] [int] NULL,
    [name] [varchar](100) NULL,
    [quantity] [numeric](18, 2) NULL
)
insert into [Warehouse]
select 1,'Door',30
union all
select 2,'Wheel',30
union all
select 3,'Light',30

CREATE TABLE [dbo].[Relation](
    [assembly_id] [int] NULL,
    [required_item] [int] NULL,
    [required_quantity] [int] NULL
)
insert into [relation]
select 1,1,10
union all
select 1,2,10
union all
select 1,3,10
union all
select 2,1,3
union all
select 2,2,3
union all
select 2,3,3

测试关系

select * from Assembly as a
inner join Relation as r on r.assembly_id = a.id_item
inner join Warehouse as w on w.id_item = r.required_item

结果是

id_item name    quantity    assembly_id required_item   required_quantity   id_item name    quantity
1   Car_A   0   1   1   10  1   Door    30.00
1   Car_A   0   1   2   10  2   Wheel   30.00
1   Car_A   0   1   3   10  3   Light   30.00
2   Car_B   0   2   1   3   1   Door    30.00
2   Car_B   0   2   2   3   2   Wheel   30.00
2   Car_B   0   2   3   3   3   Light   30.00

在这里你的解决方案

select a.name,min(a.new_quantity) as new_quantity 
from (
select a.name,floor(w.quantity/r.required_quantity) as new_quantity 
from Assembly as a
inner join Relation as r on r.assembly_id = a.id_item
inner join Warehouse as w on w.id_item = r.required_item
) as a
group by a.name
name    new_quantity
Car_A   3
Car_B   10

你可以尝试编辑你的工具,看看它是否正确。希望这有帮助:)