a simple way to sum a result from UNION in MySql

前端 未结 5 1249
北海茫月
北海茫月 2020-12-24 06:03

I have a union of three tables (t1,t2,t3). Each rerun exactly the same number of records, first column is id, second amount:

1  10
2  20
3  20

1  30
2  3         


        
5条回答
  •  [愿得一人]
    2020-12-24 06:40

    Not sure if MySQL uses common table expression but I would do this in postgres:

    WITH total AS(
                  SELECT id,amount AS amount FROM table_1 UNION ALL
                  SELECT id,amount AS amount FROM table_2 UNION ALL
                  SELECT id,amount AS amount FROM table_3
                 )
    SELECT id, sum(amount)
      FROM total
    

    I think that should do the trick as well.

提交回复
热议问题