2011-03-14 46 views
2

有誰知道一種方法來簡化這個WHERE表達式?SQL 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 
         ) 
       ) 
+1

你能發表整個聲明嗎? – steinar 2011-03-14 21:21:41

回答

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是一個非NULLABLE場。

+0

COALESCE的開銷是多少? – CodeGrue 2011-03-16 13:01:32

+0

@CodeGrue在這種情況下幾乎可以忽略不計 – RichardTheKiwi 2011-03-16 19:04:25

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 
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同時匹配,子查詢返回CharacteristicSpecialties_Id和where成功
  • 如果只是ModalityVariants_Id匹配,子查詢返回不同的ID ,並且where失敗
  • 如果兩者都不匹配,則子查詢返回NULL,C OALESCE返回@UserSpecialtyID和where成功

也許最明顯的是各種約翰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 

我會投票給約翰的回答:)

+0

爲什麼會增加併發症?在我看來,Coalesce和SubQuery實際上會讓這個運行變慢。不會左連接更容易? – 2011-03-14 21:28:38

+0

@John Hartsock:好吧,左連接可能會添加額外的行,如果多行包含匹配的'CharacteristicsSpecialties_ID' – Andomar 2011-03-14 21:33:14

0

我假定這是一個在桌子上ModalityVariants

將這項工作(該SQL未經測試)一個SELECT的WHERE子句?

SELECT * 
FROM ModalityVariants 
LEFT OUTER JOIN ModalityVariantSpeciality 
       ON ModalityVariants.Id = ModalityVariants_ID 
WHERE CharacteristicSpecialities_Id = @UserSpecialityID or  
     CharacteristicSpecialities_Id is NULL