[英]Calculating sum between related tables
I created a test database so I can illustrate my problem: 我创建了一个测试数据库,以便说明我的问题:
create table A(
id int(11) primary key not null,
price decimal(10,2)
);
create table B(
id int(11) primary key not null,
id_a int(11) not null,
foreign key(id_a) references A(id)
on update cascade
on delete restrict
);
insert into A values
(1,25),
(2,30),
(3,35);
insert into B values
(1,1),
(2,1),
(3,2),
(4,2),
(5,3);
That is a simplified example of some articles(A) and their prices, and a bill(B) on which there is id of bill and foreign key that represent what article is bought. 那是一些商品(A)及其价格,以及一个票据(B)的简化示例,上面有代表购买商品的票据ID和外键。
I need query to find profit from all sold articles. 我需要查询才能从所有售出的商品中获利。 So to go through table B and and find the sum of all prices of sold articles. 因此,要遍历表B并找到已售商品所有价格的总和。
You could just join the two tables: 您可以只加入两个表:
SELECT SUM(price)
FROM a
JOIN b ON b.id_a = a.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.