如何在MySQL中组合并从三个不同的相关表中获取总和?
有三个相关表格: 操作(id、名称) 价格表(id、操作id(链接到操作表)、成本) 会计(id、价目表\u id(链接到价目表)、数量) 如何得到一张桌子,比如如何在MySQL中组合并从三个不同的相关表中获取总和?,mysql,sql,sum,left-join,inner-join,Mysql,Sql,Sum,Left Join,Inner Join,有三个相关表格: 操作(id、名称) 价格表(id、操作id(链接到操作表)、成本) 会计(id、价目表\u id(链接到价目表)、数量) 如何得到一张桌子,比如 NAME SUMMARY_COST SUMMARY_QUANTITY milling result of 2*750 2 threading result of 1*444 1 ...
NAME SUMMARY_COST SUMMARY_QUANTITY
milling result of 2*750 2
threading result of 1*444 1
... ... ...
overall 2*750+1*444+... 2+1+...
我尝试一开始就分组两张表:
select operations.name, sum(pricelists.cost) total
from operations
left join pricelists on pricelists.operations_id*accounting_quantity = operations.id*accounting.quantity
group by operations.id
但它还没有起作用
一个小数据库:
CREATE TABLE operations (id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR (100));
CREATE TABLE pricelists (id INT PRIMARY KEY, operations_id INT NOT NULL, cost DECIMAL(10,2),
FOREIGN KEY (operations_id) REFERENCES operations (id));
CREATE TABLE accounting (id INT PRIMARY KEY, pricelists_id INT NOT NULL, quantity INT,
FOREIGN KEY (pricelists_id) REFERENCES pricelists (id));
INSERT INTO operations (name) VALUES
('milling'),
('threading'),
('grinding'),
('welding'),
('brazing'),
('soldering'),
('riveting');
INSERT INTO pricelists (id, operations_id, cost) VALUES
(1, 2, 750),
(2, 1, 444),
(3, 3, 123),
(4, 4, 450),
(5, 5, 375),
(6, 6, 250),
(7, 7, 232);
INSERT INTO accounting (id, pricelists_id, quantity) VALUES
(1, 7, 2),
(2, 2, 5),
(3, 4, 2),
(4, 1, 1),
(5, 3, 4);
康斯特尔:
select o.name, sum(a.quantity * pl.cost) total, sum(a.quantity) quantity
from operations o
left join pricelists pl on pl.operations_id = o.id
left join accounting a on a.pricelists_id = pl.id
group by o.name
您只需在查询的最后添加带有rollup的
,即可生成摘要行。谢谢!它起作用了。可以添加最后一行“总体”,这表示列的总和吗?@antonio_fergusson:答案中已经提到了这一点。只需在查询的最后添加带有rollup的。