2012-09-25 107 views
5

我有我這樣的表。SQL選擇不同於where子句

PersonID, KvalifikationId 
1   1 
1   2 
1   3 
2   1 
2   3 

我想要寫SQL querye返回所有的人,有沒有kvalifikation 2.

我寫

SELECT DISTINCT PersonID where NOT KvalifikationID = 2 

但是,這回人都1和患者2 我該怎麼辦選擇只返回沒有kval2的personId?

回答

7

試試這個,

SELECT DISTINCT PersonID 
FROM tableName 
WHERE PersonID NOT IN 
    (
     SELECT PersonID 
     FROM tableName 
     WHERE KvalifikationId = 2 
    ) 

SQLFiddle Demo

+0

Ty,工作正常。 –

+0

@歡迎您光臨! –

3
SELECT DISTINCT person_id 
FROM tableName t1 
WHERE not exists 
(
    select 1 
    from tableName 
    where person_id = t1.person_id and KvalifikationId = 2 
) 
3
Declare @t table(PersonID int,KvalifikationId int) 
Insert Into @t Select 1 ,1 
Insert Into @t Select 1, 2 
Insert Into @t Select 1,3 
Insert Into @t Select 2 ,1 
Insert Into @t Select 2,3 

Select PersonId From @t 

Except 

Select PersonID From @t where KvalifikationId = 2 

結果

PersonId 
2 
-1

嘗試。
SELECT DISTINCT PersonName from tableName
WHERE KvalifikationId NOT IN('2');

3

通過使用您的Person表而不是外部查詢中的N:N表,您可以跳過distinct,並且反向半連接到子查詢將具有更好的性能,因爲它位於聚簇索引上。 (假設PersonIDPerson表中的pk)

SELECT PersonID 
FROM tblPerson 
WHERE NOT EXISTS 
    (
     SELECT NULL 
     FROM tblPersonKvalifikation 
     WHERE KvalifikationId = 2 AND 
       tblPerson.PersonID = tblPersonKvalifikation.PersonID 
    )