2014-05-06 45 views
4

這個標題聽起來很混亂,所以讓我展示一下我需要的東西。將兩個表格中的一列中的一列的值總結到第三個表格中

table1

name number 
Bob 6 
Linda 8 
Tina 3 

table2

name number 
Bob 9 
Linda 2 
Tina 1 

我需要的是對的number值總結到第三個表(已存在),因此它看起來像這樣:

table3

name number 
Bob 15 
Linda 10 
Tina 4 

對不起,如果這已經得到了答覆,但我儘可能搜索,我可以和所有的答案是真正具體到這個問題,並沒有完全做我所需要的。

編輯:table3目前完全空白。它只是與table1table2共享相同的結構。

回答

5

這是你如何做到這一點:

insert into table3 (name, number) 
    select t.name, sum(t.number) as totalNumber 
    from (
     select name, number from table1 
     union 
     select name, number from table2 
     union 
     select name, number from table3 
    ) t 
    group by t.name 

如果你想爲特定name的summry數據,你可以添加此where子句中group by這樣上面:

where t.name = 'Bob' 
+0

爲了插入到表3中,在第一行添加INSERT table3(name,number)'。 –

+0

我應該在我的文章中提到過,我幾乎不知道MySQL。我究竟如何將這些數據插入'table3'?請記住,'table3'是完全空白的,它與'table1'和'table2'具有相同的結構。 – user3201643

+1

它非常簡單(結合'insert into'與'select'),我已經更新了我的答案。 – Latheesan

1

如果你已經有了table3,你可以使用下面的查詢做所有的名字,並且使用所有名字的循環。

insert into table3 (number) values (select (t1.number + t2.number) from table1 inner join table2 on t1.name = t2.name where t1.name = 'Bob') 

否則您需要編寫程序。

+1

爲什麼不'select' +'union' +'組by'? – Latheesan

+0

你是對的@Latheesan Kanes –

0

您的預期結果...!!! (簡單和排序查詢)

  INSERT INTO table3 (name,number) 
      SELECT t.name, sum(t.number) as number 
      FROM (
       SELECT name, number from table1 
       UNION 
       SELECT name, number from table2 
     ) t 
      GROUP BY t.name 

結果: -

表3:

  name number 
      Bob  15 
      Linda 10 
      Tina  4 
+0

對不起,我不得不提問;你只是複製我的答案?大聲笑。 – Latheesan

+0

不,親愛的.. !! 其實你是寫和發佈答案我是搜索和執行查詢在我的數據庫,並最終找到查詢和發佈後,你的答案檢查。非常抱歉。 –

相關問題