mysql - 如何在 View 中使用 MySQL UNION 和 SUM

标签 mysql

我有 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/

相关文章:

mysql - 使用 max() 获取表中的最新行,加入另一个表

mysql - 将数据库从本地主机更改为外部主机

mysql - mysql中使用concat创建复合索引

c# - 使用 C# 将十进制值插入 MySQL

java - 在SQL中使用一个命令 - 我需要将单词 'Cars' 的所有实例更改为 'Zip-Cars' ,这包括将 'Cars 2' 更改为 'Zip-Cars 2'

php - 如何在数据库中存储多语言网站信息?

mysql - .com.mysql.jdbc.exception.jbbc4.communicationException..通信链路故障

php - 通过php将CSV文件中的数据导入到Mysql表中

MySQL 用于平均缺失日期

java - 在 ubuntu 18.04 中通过 eclipse 与 mySql(mysql 5.7.22) 进行 JDBC 连接时出现错误