如何在视图中使用MySQL UNION和SUM

时间:2017-01-23 14:28:59

标签: mysql

我有2张桌子

表一:

id   amount
1    2
1    1
2    1

表二:

id   amount
1    2

我希望使用输出生成视图:

观点:

id   amount
1    5
2    1

我尝试使用像我这样的简单代码

CREATE VIEW v_test AS
SELECT id, sum(amount)
FROM table1
UNION ALL
SELECT id, sum(amount)
FROM table2
GROUP BY id

但是当我在输出上面运行SQL时:

id   amount
1    2
1    3
2    1

我想要的任何输出代码? 谢谢

3 个答案:

答案 0 :(得分:3)

查看您的数据示例并执行以下事实:某些mysql版本不允许在视图中进行subselect,您可以创建实用程序视图

create view v_test_union 
as  
  select id, amount
  from table1
  union all 
  select id, amount
  from table2

然后创建您的视图

create view 
as 
  select id, sum(amount)
  from v_test_union

如果您使用mysql 5.7或更高版本,则可以在create view语句中使用子查询:

create view 
as 
    select id, sum(amount)
    from 
        (select id, amount
         from table1
         union all 
         select id, amount
         from table2) t
  group by id

答案 1 :(得分:1)

你也可以使用下面的连接

来使用它
CREATE VIEW v_test AS
SELECT table1.id as id,(sum(table1.amount)+sum(table2.amount)) as amount FROM table1
join table2 on table1.id=table2.id
GROUP BY table1.id

答案 2 :(得分:0)

SQL DEMO

CREATE VIEW v_test AS
SELECT id, SUM(amount)
FROM (
        SELECT id, amount
        FROM table1
        UNION ALL
        SELECT id, amount
        FROM table2
     ) t
GROUP BY id     
;

<强>输出

enter image description here