简体   繁体   English

SQL选择与where子句不同

[英]SQL select Distinct with where clause

I have i table like this. 我有这样的表。

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

I want to write SQL querye returning all persons, that have not kvalifikation 2. 我想编写SQL querye返回所有没有kvalifikation 2的人。

i Wrote 我写

SELECT DISTINCT PersonID where NOT KvalifikationID = 2

But this return both person 1 and person 2. How do i make select that only return personId's that not have kval2 ? 但是这将返回人1和人2.我如何选择只返回没有kval2的personId?

Try this, 试试这个,

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

SQLFiddle Demo SQLFiddle演示

SELECT DISTINCT person_id
FROM tableName t1
WHERE not exists 
(
  select 1 
  from tableName 
  where person_id = t1.person_id and KvalifikationId = 2 
)
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

Result 结果

PersonId
2

By using your Person table rather than your N:N table in the outer query you can skip the distinct and the anti semi join to the sub query will have better performance since it is on a clustered index. 通过在外部查询中使用Person表而不是N:N表,可以跳过distinct ,而对于子查询的反半连接将具有更好的性能,因为它在聚簇索引上。 (assuming PersonID is pk in the Person table) (假设PersonIDPerson表中的pk)

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

try this. 试试这个。
SELECT DISTINCT PersonID from tableName 从tableName中选择DISTINCT PersonID
WHERE KvalifikationId NOT IN ('2'); KvalifikationId不在('2');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM