我需要在mysql上创建一个视图,其中查询具有带变量的不同类别名称。变量用于为每个类别生成id。
这是我的sql,任何人都可以帮助我,因为我无法使用这种SQL语法创建视图。
create view cat1_view as (SELECT distinct categorylev1,
@rownum := @rownum + 1 AS id
FROM topic t,
(SELECT @rownum := 0) r
group by categorylev1)
答案 0 :(得分:0)
这样的东西?
/*
create temporary table t(can_id int, status varchar(20));
insert into t values
(001 , 'section 1 question 1'),
(001 , 'section 1 question 2'),
(001 , 'section 1 question 3'),
(001 , 'section 1 question 4'),
(001 , 'section 2 question 1'),
(001 , 'section 2 question 2'),
(001 , 'section 2 question 3'),
(001 , 'section 2 question 4'),
(001 , 'section 3 question 1'),
(001 , 'section 3 question 2'),
(001 , 'section 3 question 3'),
(002 , 'section 1 question 1'),
(002 , 'section 1 question 2'),
(002 , 'section 1 question 3'),
(002 , 'section 2 question 1'),
(002 , 'section 2 question 2'),
(002 , 'section 2 question 3'),
(002 , 'section 3 question 1'),
(002 , 'section 3 question 2'),
(002 , 'section 3 question 3'),
(002 , 'section 3 question 4');
*/
select distinct s.canid from
(
select t.can_id as tcanid, t.status as tstatus ,
case when @previd <> substring(t.status,1,9) then
@sno :=if(@previd <> substring(t.status,1,9),@sno + 1,1)
else @sno
end as canid
,@previd:=substring(t.status,1,9) prevcanid
from t,
(select @sno:= 0) as sn
,(select @Previd:= '') as p
order by substring(t.status,1,9)
) s