我有两个表Master - Detail并试图根据输入参数找到更相关的结果
Create Table #Master(MasterId int, Method varchar(100))
Insert Into #Master Values(1,'MasterDefault')
Create Table #Detail(Id int, MasterId int,ATypeId int, BTypeId int,CTypeId int,DetailMethod varchar(100))
Insert Into #Detail
Values(1,1,1,1,1,'Detail All'),
(2,1,null,1,1,'Detail ATypeId null'),
(3,1,null,null,1,'Detail ATypeId and Btype null'),
(4,1,null,null,null,'Detail all null')
开始下面的内容(我想要找的只是方法,无论是主人还是细节)
declare @Id int =1,
@AtypeId int =1,
@BtypeId int=1,
@CtypeId int =1
Select *
from #Master M
left outer join #Detail D on M.MasterId = D.MasterId
Where M.MasterId = @Id
AND ((D.ATypeId=@AtypeId) OR (D.ATypeId IS NULL))
AND ((D.BTypeId=@BtypeId) OR (D.BTypeId IS NULL))
AND ((D.CTypeId=@CtypeId) OR (D.CTypeId IS NULL))
在这种情况下,想要返回Detail - Id 1记录,因为所有输入都与详细信息row1匹配
ID参数如下
declare @Id int =1,
@AtypeId int =null,
@BtypeId int=1,
@CtypeId int =1
期望来自详细信息的行与Id 2
有关实现此目的的任何帮助
答案 0 :(得分:1)
简单AND/OR
逻辑对您有用。
SELECT *
FROM #Master M
LEFT OUTER JOIN #Detail D
ON M.MasterId = D.MasterId
AND ( D.ATypeId = @AtypeId
OR ( @AtypeId IS NULL
AND AtypeId IS NULL ) )
AND ( D.BTypeId = @BtypeId
OR ( @BtypeId IS NULL
AND BtypeId IS NULL ) )
AND ( D.CTypeId = @CtypeId
OR ( @CtypeId IS NULL
AND CtypeId IS NULL ) )
WHERE M.MasterId = @Id
注意:由于您使用了ON
,我已将右表过滤器移至LEFT OUTER JOIN
条件。当您使用LEFT OUTER JOIN
并过滤Where
子句中的右表记录时,它将隐式转换为INNER JOIN