how to make inner join query for getting multiple tables selected column

47 Views Asked by At

i just working out project school management. now i just made query for retrieve other table columns. here is my query :

ALTER PROCEDURE [dbo].[GetTeacherList]
(
    @teacherid varchar(5) = null,
    @classid varchar(5) = null,
    @sectionid varchar(5) = null,
    @subjectid varchar(5) = null
)
AS
BEGIN

    SET NOCOUNT ON;
    select *,right('00000' + CAST(t.[PK_PID] AS varchar(5)) ,5) as ID, c.ClassName, su.SubjectName, s.SectionName
    from teachers t 

        inner join teacherclassassign tc on t.PK_PID = tc.TeacherID or (t.PK_PID is null and tc.TeacherID is null ) 
        inner join classes c on c.PK_PID = tc.ClassID or (c.PK_PID is not null and tc.ClassID is null)
        inner join sections s on s.PK_PID = tc.SectionID or (s.PK_PID is not null and tc.SectionID is null)
        inner join subjects su on su.PK_PID = tc.SubjectID or (su.PK_PID is not null and tc.SubjectID is null)

    where 1=1

    and (@teacherid is null or tc.[TeacherID] = CONVERT(INT,@teacherid))
    and (@classid is null or tc.[ClassID] = CONVERT(INT,@classid))
    and (@sectionid is null or tc.[SectionID] = CONVERT(INT,@sectionid))
    and (@subjectid is null or tc.[SubjectID] = CONVERT(INT,@subjectid))

    order by t.PK_PID asc
END

how ever it's return me two rows how ever i want all rows from table teachers.

here is rows data i want :

enter image description here

and here is all data of teachers :

enter image description here

how i achieve this result..please guys help me.

1

There are 1 best solutions below

0
Zee786 On

You need to replace the first inner join with the LEFT Join as you want all teachers.

Below i have changed the query,See if this fixes the problem

SET NOCOUNT ON; select *,right('00000' + CAST(t.[PK_PID] AS varchar(5)) ,5) as ID, c.ClassName, su.SubjectName, s.SectionName from teachers t

    LEFT join teacherclassassign tc on t.PK_PID = tc.TeacherID or (t.PK_PID is null and tc.TeacherID is null ) 
    inner join classes c on c.PK_PID = tc.ClassID or (c.PK_PID is not null and tc.ClassID is null)
    inner join sections s on s.PK_PID = tc.SectionID or (s.PK_PID is not null and tc.SectionID is null)
    inner join subjects su on su.PK_PID = tc.SubjectID or (su.PK_PID is not null and tc.SubjectID is null)

where 1=1

and (@teacherid is null or tc.[TeacherID] = CONVERT(INT,@teacherid))
and (@classid is null or tc.[ClassID] = CONVERT(INT,@classid))
and (@sectionid is null or tc.[SectionID] = CONVERT(INT,@sectionid))
and (@subjectid is null or tc.[SubjectID] = CONVERT(INT,@subjectid))

order by t.PK_PID asc

END