I have two tables, for example 1st has id, and name. 2nd has id, link to 1st table by id and COST.
CREATE TABLE FIRST_TABLE (id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR (100));
CREATE TABLE SECOND_TABLE (id INT PRIMARY KEY, FIRST_TABLE_ID INT NOT NULL, cost DECIMAL(10,2),
FOREIGN KEY (FIRST_TABLE_ID) REFERENCES FIRST_TABLE (ID));
INSERT INTO FIRST_TABLE (NAME) VALUES
('ONE'),
('TWO'),
('THREE');
INSERT INTO SECOND_TABLE (ID, FIRST_TABLE_ID, COST) VALUES
(1, 1, 500),
(2, 2, 400),
(3, 3, 150),
(4, 1, 500),
(5, 2, 400),
(6, 3, 150);
How to get sum of elements COST (of 2nd table), which depends on NAME (of 1st table)?
What i tried to do:
select FIRST_TABLE.NAME, sum(SECOND_TABLE.COST) TOTAL_COST
from FIRST_TABLE
left join SECOND_TABLE on FIRST_TABLE_ID = SECOND_TABLE.ID
group by FIRST_TABLE.ID
The problem is: I have only irregular sum of cost - 1050 for every NAME. ONE - 1050 TWO - 1050 THREE - 1050
How to get genuine values for every NAME?
And how will it look like if i have three tables and for key in 1st i have to get sum of 2nd table and 3rd table?