--
-- ### Advanced left outer join check with null value comparison
--


drop if exists table teacher;
drop if exists table grade;
drop if exists table employment;
drop if exists view empview;

create table teacher ( tchid int, firstname string(20), lastname string(20), gradeid int, cltid int);
create table grade ( gradeid int, gradename string(20), gcltid int);
create table employment ( empid int, tchid int, started datetime, ended datetime);


insert into teacher values ( 1, 'Hans', 'Maier', 1, 10);
insert into teacher values ( 2, 'Bernd', 'Müller', 1, 10 );
insert into teacher values ( 3, 'Iwan', 'Hahn', 1, 10 );

insert into grade values ( 1, 'GradeA', 1);
insert into grade values ( 2, 'GradeB', 1);

insert into employment values ( 1, 2, '01.01.2026', '31.12.2026');
insert into employment values ( 2, 3, '01.01.2026', '31.12.2026');
insert into employment values ( 3, 2, '01.01.2026', '31.12.2026');

-- Native join return result as expected for tchid 1
select t.tchid as tchid,
       t.firstname as firstname,
       t.lastname as lastname,
       g.gradename as gradename,
       e.empid as empid,
       e.started as started,
       t.cltid as ccltid,
       g.gcltid as gcltid
from teacher t
left outer join employment e on e.tchid = t.tchid
left outer join grade g on t.gradeid = g.gradeid
where ( t.cltid = 1 or g.gcltid = 1 ) and e.empid is null;

create view empview as
select t.tchid as tchid,
       t.firstname as firstname,
       t.lastname as lastname,
       g.gradename as gradename,
       e.empid as empid,
       e.started as started,
       t.cltid as ccltid,
       g.gcltid as gcltid
from teacher t
left outer join employment e on e.tchid = t.tchid
left outer join grade g on t.gradeid = g.gradeid;

-- With version 2.54.2, the view join returns wrong result with entries for tchid 1, 2 and 3
select tchid, firstname, lastname, ccltid, gcltid, empid
from empview where ( ccltid = 1 or gcltid = 1 ) and empid is null;

-- View join returns right result with entries for tchid 1
-- with splitted condition
 select tchid, firstname, lastname, ccltid, gcltid, empid
 from empview
 where ( ccltid = 1 and empid is null ) or ( gcltid = 1 and empid is null );







