Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 选择映射表中只有一条记录的查询_Sql Server_Tsql - Fatal编程技术网

Sql server 选择映射表中只有一条记录的查询

Sql server 选择映射表中只有一条记录的查询,sql-server,tsql,Sql Server,Tsql,请问,有人能帮我一个简单的问题吗 我们有两张结构如下的桌子 客户表格: +----+-----------+ | id | name | +----+-----------+ | 1 | customer1 | | 2 | customer2 | | 3 | customer3 | +----+-----------+ 客户角色映射表: +-------------+-----------------+ | customer_id | customerRole_id | +--

请问,有人能帮我一个简单的问题吗

我们有两张结构如下的桌子

客户
表格:

+----+-----------+
| id |   name    |
+----+-----------+
|  1 | customer1 |
|  2 | customer2 |
|  3 | customer3 |
+----+-----------+
客户角色
映射表:

+-------------+-----------------+
| customer_id | customerRole_id |
+-------------+-----------------+
|           1 |               1 |
|           1 |               2 |
|           2 |               1 |
|           3 |               1 |
|           4 |               1 |
|           5 |               1 |
+-------------+-----------------+
我想选择角色id为1的客户,而不是角色id为1和2的客户

因此,在这种情况下,它将是客户id 2、3、4和5。忽略1,因为它有多个角色

是否有一个简单的查询来实现这一点


非常感谢您提供的帮助。

嗯,有几种方法可以做到这一点

select c.*
from customers c
where exists (select 1 from mapping m where m.customerid = c.id and m.role = 1) and
      not exists (select 1 from mapping m where m.customerid = c.id and m.role <> 1);

此解决方案假定
角色
从不为

非常感谢,因为响应如此之快-我将尝试此解决方案。第二个解决方案非常适合我的需要:-)谢谢!
select customerid
from mapping
group by customerid
having min(role) = 1 and max(role) = 1;