MySQL错误1351无法创建视图

时间:2018-04-27 19:19:00

标签: mysql finance

下面是我正在尝试使用创建视图的查询。当我运行它时,“我得到错误代码:1351。视图的SELECT包含一个变量或参数”。这是什么情况,有一种解决方法,我可以创建一个视图,而不会改变我当前查询中的太多内容吗?

谢谢!

create view delta as
select rnk2.`date`, 
case when rnk1.r1=1 and rnk2.r2=1 then rnk1.X else rnk2.X-rnk1.X end as 'Daily Total'
from (
  select `date`,X,@r1:=@r1+1 as r1
  from  samples, (select @r1:=0) a 
  order by `date` ) rnk1
inner join 
  (select `date`,X,@r2:=@r2+1 as r2
   from  samples, (select @r2:=0) b
   order by `date`) rnk2
on (rnk1.r1=1 and rnk2.r2=1) or (rnk1.r1+1=rnk2.r2) 
order by rnk2.`date`;

1 个答案:

答案 0 :(得分:0)

mySQL视图不允许用户变量或子查询,因此我更改了查询并将视图拆分为两部分。

第一个视图将根据日期在表SAMPLE上分配行号。然后第二个视图将使用第一个视图(sample_vw)来执行主查询。

create view sample_vw as
select a.`date`, a.X, count(*) as rn
FROM samples a
JOIN samples b 
ON a.`date` >= b.`date`
GROUP BY a.`date`;

create view delta as
SELECT t1.`date`,
case when t1.rn=1 and t2.rn=1 then t1.X else t2.X-t1.X end as 'Daily Total'
FROM sample_vw t1
INNER JOIN sample_vw t2
ON t1.rn+1=t2.rn or (t1.rn=1 and t2.rn=1);