SQL WHERE在多对多或多对多空

时间:2011-03-14 21:12:57

标签: sql sql-server

有没有人知道简化这个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
                        )
                ) 

4 个答案:

答案 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)
  • 如果ModalityVariants_Id和UserSpecialtyID都匹配,则子查询返回CharacteristicsSpecialties_Id,where成功
  • 如果只有ModalityVariants_Id匹配,则子查询返回不同的ID,where失败
  • 如果两者都不匹配,则子查询返回NULL,COALESCE返回@UserSpecialtyID,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