有没有人知道简化这个WHERE表达式的方法?
WHERE (
(@UserSpecialtyID in
(
SELECT CharacteristicSpecialties_Id
FROM ModalityVariantSpecialty
WHERE ModalityVariants_Id = ModalityVariants.Id
)
)
OR
NOT EXISTS
(
SELECT CharacteristicSpecialties_Id
FROM ModalityVariantSpecialty
WHERE ModalityVariants_Id = ModalityVariants.Id
)
)
答案 0 :(得分:2)
这样的事情可能会起作用,但我对你们桌子的关系并不十分清楚。如果你能解释一下这种关系,我可能会举一个更好的例子。
SELECT
*
FROM MadalityVariants mv
LEFT JOIN ModalityVariantSpecialty mvs on mvs.ModalityVariants_ID = mv.ID
WHERE
@UserSpecialtyID = mvs.CharacteristicSpecialties_ID
OR
mvs.CharacteristicSpecialties_ID is null
答案 1 :(得分:1)
WHERE (
@UserSpecialtyID in
(
SELECT COALESCE(CharacteristicSpecialties_Id, A.A)
FROM (SELECT @UserSpecialtyID A) A LEFT JOIN ModalityVariantSpecialty
ON ModalityVariants_Id = ModalityVariants.Id
)
)
如果CharacteristicSpecialties_Id
是一个NON NULLABLE字段,这很有效。
答案 2 :(得分:0)
这是我的尝试:
WHERE @UserSpecialtyID = COALESCE
(
SELECT TOP 1 CharacteristicSpecialties_Id
FROM ModalityVariantSpecialty
WHERE ModalityVariants_Id = ModalityVariants.Id
ORDER BY
CASE WHEN CharacteristicSpecialties_Id = UserSpecialtyID THEN 1
ELSE 2 END ASC
), @UserSpecialtyID)
where
成功where
失败where
成功可能最清楚的是John Hartsock的各种答案,使用子查询来确保left join
不添加任何行。
select *
from ModalityVariants mv
left join
(
select distinct ModalityVariants_ID
, CharacteristicSpecialties_ID
from ModalityVariantSpecialty
) as mvs
on mvs.ModalityVariants_ID = mv.ID
where @UserSpecialtyID = mvs.CharacteristicSpecialties_ID
OR
mvs.CharacteristicSpecialties_ID is null
我会投票支持约翰的答案:)
答案 3 :(得分:0)
我假设这是表ModalityVariants
上的SELECT的WHERE子句这是否有效(SQL未经过测试)?
SELECT *
FROM ModalityVariants
LEFT OUTER JOIN ModalityVariantSpeciality
ON ModalityVariants.Id = ModalityVariants_ID
WHERE CharacteristicSpecialities_Id = @UserSpecialityID or
CharacteristicSpecialities_Id is NULL