如何查询表中的多个条件

时间:2014-12-08 17:55:18

标签: sql sql-server tsql stored-procedures

假设我有一组包含业务分析师,质量保证分析师等数据的角色表。所有都由唯一ID索引。 我有另一个表,人们再次使用唯一的ID索引。

我为具有多个角色名为“PersonRole”的人创建了第三个表格。如果我想为具有业务分析师和开发人员角色的人(假设Id为2和3)查询PersonRole,我需要什么类型的查询?我应该使用子查询或联合构建它吗?

我试过这个,但没有回复。

select * from PersonRole 
inner join Person on Person.Id = PersonRole.PersonId
where Person.Id = 3
and PersonRole.RoleId = 2
and PersonRole.RoleId = 3

4 个答案:

答案 0 :(得分:2)

您可以使用OR

select * from PersonRole 
inner join Person on Person.Id = PersonRole.PersonId
where Person.Id = 3
and (PersonRole.RoleId = 2 OR PersonRole.RoleId = 3)

另外IN

select * from PersonRole 
inner join Person on Person.Id = PersonRole.PersonId
where Person.Id = 3
and PersonRole.RoleId IN (2,3)

答案 1 :(得分:1)

试试这个:

select * from PersonRole 
inner join Person on Person.Id = PersonRole.PersonId
where Person.Id = 3
OR PersonRole.RoleId = 2 OR
PersonRole.RoleId = 3

OR

select * from PersonRole 
inner join Person on Person.Id = PersonRole.PersonId
where Person.Id = 3
OR PersonRole.RoleId IN (2 ,3)

答案 2 :(得分:1)

如果要查询同时拥有这两种角色的人,我建议使用having子句进行聚合查询。这是写这个的一种方法:

select pr.PersonId
from PersonRole pr
group by pr.PersonId
having sum(case when pr.RoleId = 2 then 1 else 0 end) > 0 and
       sum(case when pr.RoleId = 3 then 1 else 0 end) > 0;

如果您需要Person表中的更多详细信息,可以将其加入。

答案 3 :(得分:0)

或加入personRole两次,一次针对您想要的每个条件:

select p.* from 
Person p inner join
PersonRole r2 on 
p.Id = r2.PersonId and
r2.RoleId = 2 inner join
PersonRole r3 on 
p.Id = r3.PersonId and
r3.RoleId = 3
where 
p.Id = 3