--
-- ### Nested subqueries in selection
-- 
-- 
--

drop if exists table ma_system; 
create table ma_system ( 
    sysid int not null, 
    sysname string(100) not null, 
    sysdesc string(1000), 
    tpid int not null); 

drop if exists table ma_feature2sys; 
create table ma_feature2sys ( 
       ftid int not null, 
       sysid int not null); 
create primary btree on ma_feature2sys(ftid, sysid); 


drop if exists table ma_feature2type; 
create table ma_feature2type ( 
    ftid int not null, 
    tpid int not null, 
    ismandatory string(1)); 

create primary btree on ma_feature2type(ftid, tpid); 


insert into ma_feature2type ( ftid, tpid, ismandatory ) values ( 1, 1, 'Y'); 
insert into ma_feature2type ( ftid, tpid, ismandatory ) values ( 1, 2, 'N'); 
insert into ma_feature2type ( ftid, tpid, ismandatory ) values ( 1, 3, 'Y'); 

insert into ma_feature2type ( ftid, tpid ) values ( 2, 2); 
insert into ma_feature2type ( ftid, tpid ) values ( 2, 3); 
insert into ma_feature2type ( ftid, tpid ) values ( 3, 3); 

insert into ma_system ( sysid, sysname, tpid ) values ( 1, 'hugo', 3 ); 
insert into ma_feature2sys ( ftid, sysid ) values ( 1, 1); 
insert into ma_feature2sys ( ftid, sysid ) values ( 2, 1); 
insert into ma_feature2sys ( ftid, sysid ) values ( 3, 1); 

drop if exists view ma_view; 
create view ma_view 
as 
select 
        f2s.sysid,
	f2s.ftid,
        ( select ismandatory from ma_feature2type f2t where f2t.tpid = ( select tpid from ma_system where sysid = f2s.sysid ) and f2t.ftid = f2s.ftid ) as ismandatory 
from ma_feature2sys f2s; 

select ismandatory from ma_feature2type f2t where f2t.tpid = ( select tpid from ma_system where sysid = 1 );

select * from ma_view; 
select * from ma_view;
select * from ma_view;
select * from ma_view;
