如何进行内部联接查询以获取多个选定的表列

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何进行内部联接查询以获取多个选定的表列相关的知识,希望对你有一定的参考价值。

我只是制定项目学校的管理。现在我只是查询以检索其他表列。这是我的查询:

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

如何返回我两行,但是我希望从表教师那里得到所有行。

这里是我想要的行数据:

enter image description here

这里是老师的全部数据:

enter image description here

我如何达到这个结果。请大家帮我。

答案

[您需要所有教师都需要用LEFT Join替换第一个内部join。

下面我更改了查询,看看是否可以解决问题

将NOCOUNT设为ON;选择*,right('00000'+ CAST(t。[PK_PID] AS varchar(5)),5)作为ID,c.ClassName,su.SubjectName,s.SectionName来自老师们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

以上是关于如何进行内部联接查询以获取多个选定的表列的主要内容,如果未能解决你的问题,请参考以下文章

有没有办法改进这个查询

忽略单峰的内部联接

将选定日期与表列或 MySQL 查询生成的日期数组进行比较

使用内部联接更新多个表中的列

使用 NamedQuery 进行内部联接?

如何从内部联接查询之一中获取总数?