我在sql中有这个查询: -
Select
*
from
ClassNote C
Join ClassSubMatRelation CSMR on C.ClassNoteID=CSMR.ClassNoteFK
where
CSMR.BoardFK = 1
and
CSMR.SubjectFK in
(
select
t.SubjectFK
from
ClassSubMatRelation t
where
t.BoardFK = 1
)
and
CSMR.SubjectFK not in
(
select
e.SubjectFK
from
ClassSubMatRelation e
where
e.BoardFK != 1
)
and
CSMR.Status_Info = 1
and
CSMR.ClassNoteFK is not null
查询工作正常。但我想我可以使用连接来使其更简单,更快捷。如你所见,我是新手,所以无法弄清楚我该怎么做。我尝试了其他解决方案,但是他们没有正常工作。
我的表架构: -
ClassNote (
ClassNoteID
Heading
ClassNoteDesc
ClassNoteRefID
Status_Info
)
ClassSubMatRelation (
ClassSubMatRelationID
BoardFK
ClassFK
SubjectFK
MaterialFK
ClassNoteFK
ClassEbookFK
ClassSPFK
Status_Info
)
答案 0 :(得分:0)
您可以通过将部分WHERE
移至JOIN
的{{1}}语句,对加入CSMR设置一些限制。
像这样:
ON
但我不认为这会加快速度。 SQL Server非常好地优化......至少它阅读起来有点简单。
编辑 - 现在我看一下,这两个IN声明是否必要? IN正在获得所有BoardFK = 1并且NOT IN确保你得到的不是1 ...... 既然你已经在那里明确指定BoardFK = 1,你就不需要那些......所以,像这样:
Select *
from ClassNote C
Join ClassSubMatRelation CSMR
on C.ClassNoteID=CSMR.ClassNoteFK
and CSMR.Status_Info=1
and CSMR.ClassNoteFK is not null
and CSMR.BoardFK = 1
where CSMR.SubjectFK in (select t.SubjectFK from ClassSubMatRelation t where t.BoardFK=1)
and CSMR.SubjectFK not in (select e.SubjectFK from ClassSubMatRelation e where e.BoardFK!=1)
注意:如果您决定将其更改为OUTER JOIN,那么这样做将不会表现相同。
答案 1 :(得分:0)
你可以尝试一下
Select
*
from
ClassNote C
Join ClassSubMatRelation CSMR on C.ClassNoteID=CSMR.ClassNoteFK AND
CSMR.BoardFK = 1
AND
CSMR.Status_Info = 1
AND
CSMR.ClassNoteFK is not null
Join ClassSubMatRelation t on t.SubjectFK = CSMR.SubjectFK AND t.BoardFK = 1
LEFT JOIN ClassSubMatRelation e ON e.SubjectFK AND e.BoardFK != 1 AND e.SubjectFK IS NULL
答案 2 :(得分:0)
我注意到你的第二个CSMR.SubjectFK
子句是多余的:第一个只匹配t.BoardFK = 1
的行,而第二个子句排除t.BoardFK != 1
的行,但它们已被排除在外第一个条款,使它完全是多余的。它们都可以替换为单个INNER JOIN
:
SELECT
ClassNote.*
FROM
ClassNote
INNER JOIN ClassSubMatRelation AS csmr ON ClassNote.ClassNoteId = csmr.ClassNoteFK
LEFT OUTER JOIN ClassSubMatRelation AS subject ON csmr.SubjectFK = subject.SubjectFK
WHERE
csmr.BoardFK = 1
AND
subject.SubjectFK = 1
AND
csmr.Status_Info = 1