我有一个非常简单和自我解释的SQL语句:
ALTER PROCEDURE [dbo].[sp_getAllDebatesForAlias](@SubjectAlias nchar(30))
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT *
FROM tblDebates
WHERE (SubjectID1 in (SELECT SubjectID FROM tblSubjectAlias WHERE SubjectAlias = @SubjectAlias))
OR (SubjectID2 in (SELECT SubjectID FROM tblSubjectAlias WHERE SubjectAlias = @SubjectAlias)) ;
END
我确信有一种方法可以使这个陈述更有效率,至少可以摆脱in
部分中同一个表的多次创建,即
SELECT SubjectID FROM tblSubjectAlias WHERE SubjectAlias = @SubjectAlias
一部分。
有什么想法吗?
答案 0 :(得分:1)
SELECT d.*
FROM tblDebates d
inner join tblSubjectAlias s on s.SubjectID in (d.SubjectID1, d.SubjectID2)
where s.SubjectAlias = @SubjectAlias
答案 1 :(得分:1)
尝试:
select d.* from tblDebates d
where exists
(select 1
from tblSubjectAlias s
where s.SubjectID in (d.SubjectID1, d.SubjectID2) and
s.SubjectAlias = @SubjectAlias)