我有 2 张 table
表一:
id amount
1 2
1 1
2 1
表二:
id amount
1 2
我想让 View 的输出如下:
查看:
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
有我想要的输出的代码吗? 谢谢
最佳答案
查看您的数据样本并了解某些 mysql 版本不允许在 View 中进行子选择的事实,您可以创建一个实用程序 View
create view v_test_union
as
select id, amount
from table1
union all
select id, amount
from table2
然后创建您的 View
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
关于mysql - 如何在 View 中使用 MySQL UNION 和 SUM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41808669/