使用变量

时间:2018-05-04 08:29:54

标签: mysql view

我想从不同的表中创建一个视图。经过2天的研究没有结果,我现在要求一些提示。

这是 op_id 表,它只存储operationID的

|  op_id  |
|---------|
| 20180101|
| 20180102|
|      ...|

对于op_id中的每个op_id - 表存在一个自己的表。例如 operations_20180101 operations_20180102 ,...

每个表的内容看起来

| username | data |
|----------|------|
|  john    |  1239|
|  adam    |   857|
|       ...|   ...|

我尝试做的是,使用所有单个表的总和(数据)创建一个视图:

| 20180101 |  3746|
| 20180102 |  4765|
|       ...|   ...|

创建简单的SQL语句

SELECT * FROM operationview

获取我需要的所有数据。

使用

SELECT op_id FROM op_id

我得到了所有的op_id。

但是从那里我不知道如何将结果存储在一个变量中并查询相应的表来创建一个像

的视图
for op_id in (SELECT op_id FROM op_id):
    CREATE VIEW overview (SELECT op_id, sum(data) FROM operations_op_id)

我从MySQL文档中获得的所有内容看起来都很简单,但并不能解决我的问题。这是我第一次尝试做比查询和子查询更复杂的事情。所以请原谅我的问题,如果解决方案更简单,那么我可以弄明白。

1 个答案:

答案 0 :(得分:0)

您可能正在寻找动态SQL,您可以在其中构建要执行的代码。例如给出

drop table if exists op_id,operations_20180101 ,operations_20180102  ;

create table op_id (op_id  int);
insert into op_id values
(20180101),
(20180102);

create table operations_20180101(username varchar(3) ,data int);
create table operations_20180102(username varchar(3) ,data int);

insert into operations_20180101 values 
('aaa',1),('bbb',2);

insert into operations_20180102 values 
('aaa',10),('bbb',20);

您可以像这样构建一个sql语句

set @sql = 
(select
replace 
(
(select 
 group_concat(concat('select ', op_id, ',sum(data) as sumdata from ',
 concat('operations_',op_id) ,
 ' union ')
 )
from
(select distinct op_id from op_id) s
) 
,'union ,','union '
)
)
;
set @sql = concat(Substring(@sql,1,length(@sql) -7),';');

哪个联合所有已定义的表并且看起来像这样

select 20180101,sum(data) as sumdata from operations_20180101 
union 
select 20180102,sum(data) as sumdata from operations_20180102;

然后可以传递给sql来执行这样的

prepare sqlstmt from @sql;
execute sqlstmt;
deallocate prepare sqlstmt;

结果

+----------+---------+
| 20180101 | sumdata |
+----------+---------+
| 20180101 |       3 |
| 20180102 |      30 |
+----------+---------+
2 rows in set (0.00 sec)