如何添加来自具有相同 ID 号的不同 table 的值?
How to add values from different table that has the same id number?
我有 7 个 table,每个 table 都有一个总计列我需要得到每个 table 的总数,它们具有相同的 ID 号,这些是 3 个样本tables:
干净table
clean_id | labor_expense | machine_expense | diesel_expense | clean_total
1 | 1000 | 2000 | 500 | 3500
2 | 2000 | 1000 | 1000 | 4500
plant_table
plant_id | labor_expense | machine_expense | plant_expense | plant_total
1 |
1000 |
2000 |
500 | 3500
2 | 2000 | 1000 | 1000 | 4500
fertilize_table
fertilize_id | labor_expense | machine_expense | fertilizer_expense | fertilize_total
1 |
1000 |
2000 |
500 | 3500
2 | 2000 | 1000 | 1000 | 4500
我怎样才能得到具有相同 ID 号的 clean_total、plant_total 和 fertilize_total 的总数?
我想把它保存到另一个table,比如total_expense,但我只得到第一个id号码的总和
total_expenses
total_id | clean_total | plant_total | fertilize_total | total_expenses
1 |
3500 |
3500 |
3500 | 10500
2 | 4500 | 4500 | 4500 | 13500
如果已知每个 ID 的行存在于所有表中,您可以简单地连接它们:
SELECT clean_id AS total_id,
clean_total + plant_total + fertilize_total AS total_expenses
FROM clean_table
JOIN plant_table ON clean_id = plant_id
JOIN fertilize_table ON clean_id = fertilize_id
我有 7 个 table,每个 table 都有一个总计列我需要得到每个 table 的总数,它们具有相同的 ID 号,这些是 3 个样本tables:
干净table
clean_id | labor_expense | machine_expense | diesel_expense | clean_total
1 | 1000 | 2000 | 500 | 3500
2 | 2000 | 1000 | 1000 | 4500
plant_table
plant_id | labor_expense | machine_expense | plant_expense | plant_total
1 | 1000 | 2000 | 500 | 3500
2 | 2000 | 1000 | 1000 | 4500
fertilize_table
fertilize_id | labor_expense | machine_expense | fertilizer_expense | fertilize_total
1 | 1000 | 2000 | 500 | 3500
2 | 2000 | 1000 | 1000 | 4500
我怎样才能得到具有相同 ID 号的 clean_total、plant_total 和 fertilize_total 的总数?
我想把它保存到另一个table,比如total_expense,但我只得到第一个id号码的总和
total_expenses
total_id | clean_total | plant_total | fertilize_total | total_expenses
1 | 3500 | 3500 | 3500 | 10500
2 | 4500 | 4500 | 4500 | 13500
如果已知每个 ID 的行存在于所有表中,您可以简单地连接它们:
SELECT clean_id AS total_id,
clean_total + plant_total + fertilize_total AS total_expenses
FROM clean_table
JOIN plant_table ON clean_id = plant_id
JOIN fertilize_table ON clean_id = fertilize_id