a simple way to sum a result from UNION in MySql

前端 未结 5 1267
北海茫月
北海茫月 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:32

    SELECT id, SUM(amount) FROM
    (
        SELECT id, SUM(amount) AS `amount` FROM t1 GROUP BY id
      UNION ALL
        SELECT id, SUM(amount) AS `amount` FROM t2 GROUP BY id
    ) `x`
    GROUP BY `id`
    

    I groupped each table and unioned because i think it might be faster, but you should try both solutions.

提交回复
热议问题