使用关系表MS-SQL过滤表

时间:2013-03-14 08:45:32

标签: sql-server

我需要在MS-SQL数据库中过滤带有关系表的表。

我明白了:

persId  persName1   catId

 4        Hans        0
 4        Hans        51
 4        Hans        73
 5        Torleif     0
 5        Torleif     5
 5        Torleif    73
 5        Torleif    76
 6        Peter       0
 6        Peter      51
 6        Peter      73
 7        Jonas       0
 7        Jonas      16
 7        Jonas      73

使用:

SELECT   distinct  tblPerson.persId
, tblPerson.persName1
, relCatPers.catId
FROM         tblPerson LEFT OUTER JOIN
             relCatPers ON tblPerson.persId = relCatPers.persId

但我需要。删除带有catId 51的那些。只出现一个名称和Id:

persId  persName1

  5         Torleif
  7         Jonas

表:

CREATE TABLE [dbo].[tblPerson](
    [persId] [int] IDENTITY(1,1) NOT NULL,
    [persName1] [varchar](255) NULL,
CONSTRAINT [PK_tblPerson] PRIMARY KEY CLUSTERED 
)


CREATE TABLE [dbo].[relCatPers](
    [rcpId] [int] IDENTITY(1,1) NOT NULL,
    [catId] [int] NOT NULL,
    [persId] [int] NOT NULL,
CONSTRAINT [PK_relCatPers] PRIMARY KEY CLUSTERED
)

3 个答案:

答案 0 :(得分:3)

试试这个:

Fiddle 1 demo here

select distinct p.persId, p.persName1 
from   tblPerson p left join 
         relCatPers c on p.persId = c.persId
where  p.persId not in
       (select persId from relCatPers where catId = 51)

或者你可以忽略relCatPers表,并在下面

<强> Fiddle 2 demo here

select p.persId, p.persName1 
from   tblPerson p 
where  p.persId not in
       (select persId from relCatPers where catId = 51)

答案 1 :(得分:1)

试试这个:

With cte as 
(Select persId,persName1,
        row_number() over (partition by persId,persName1 order by persID) as rn
 from tblPerson 
)
Select cte.persID,cte.persName1
from relCatPers
left join cte
on tblPerson.persId = relCatPers.persId
where relCatPers.catid=51  and
rn=1

答案 2 :(得分:1)

我已经编辑了查询,因此它不会返回catId,正如您的问题中所定义的那样:

SELECT distinct
       tblPerson.persId
       ,tblPerson.persName1
FROM   tblPerson
LEFT OUTER JOIN relCatPers ON tblPerson.persId = relCatPers.persId
WHERE  tblPerson.persId NOT IN 
       (SELECT persId FROM relCatPers WHERE catId = 51);

如果要添加应该遗漏人员的其他catId,可以将子查询中的WHERE子句更改为例如WHERE catId IN (16, 23, 51)