mysql错误1351无法创建视图

tag5nh1u  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(828)

下面是我试图创建视图的查询。当我运行它时,“我得到错误代码: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`;
bjg7j2ky

bjg7j2ky1#

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);

相关问题