如何从具有相同ID号的不同表中添加值?

时间:2015-01-29 18:24:34

标签: android sqlite android-sqlite multiple-tables

我有7个表,每个表都有一列我需要获得每个具有相同ID号的表的总数,这些是3个样本表:

干净的桌子

  

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的总数?

我当时想把它保存到另一个表,例如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

1 个答案:

答案 0 :(得分:1)

如果已知所有表中都存在每个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