sql - SQL Server内部连接查询从多对多关系表
问题描述
我是 SQL 编程新手,遇到以下问题。
我有 3 张桌子:
- tblMaschine (id PK, type as char(5))
- tblUse (id PK, typeOfUse varchar(255))
- tblmaschineUse (mid, uid PK 和上表的 FK)
这是多对多的关系。我在表格中插入了这些数据:
机器
id|type
--+-----
1 |M1
2 |M2
3 |M3
蓝丝
id|typeOfUse
--+---------
1 |U1
2 |U2
和
tblmaschine使用
id|type
--+-----
1 |1
1 |2
2 |1
3 |2
我想查询以查找在 table 中具有两种使用类型的maschine
类型。tblmaschine
maschineUse
我正在使用这个查询,但它什么也不返回:
select m.type
from tblmaschine as m
inner join tblmaschineUse as mu on m.id = mu.mid
inner join use as u on u.id = mu.uid
where u.typeOfUse = 'U1' and u.typeOfUse = 'U2';
我究竟做错了什么?
解决方案
一个选项使用聚合:
select m.id, m.type
from tblmaschine m
inner join tblmaschineUse mu on mu.id = m.id
where mu.type in (1, 2)
group by m.id, m.type
having count(*) = 2
这假设没有重复(id, type)
(tblmaschineUse
否则,您需要having count(distinct type) = 2
.
如果要过滤类型的名称,则需要另一个联接:
select m.id, m.type
from tblmaschine m
inner join tblmaschineUse mu on mu.id = m.id
inner join tbluse u on u.id = mu.type
where u.typeOfUse in ('U1', 'U2')
having count(*) = 2
您还可以使用两个exists
子查询:
select m.*
from tblmaschine m
where
exists(select 1 from tblmaschineUse mu inner join tbluse u on u.id = mu.type where u.typeOfUse = 'U1' where mu.id = m.id)
and exists (select 1 from tblmaschineUse mu inner join tbluse u on u.id = mu.type where u.typeOfUse = 'U2' where mu.id = m.id)
推荐阅读
- excel - 我们可以使用 Pandas 自动化 Excel 的数据过滤器吗?
- ms-access - 如何在 Access 中为多对多表输入数据?
- windows - 根据具有排除项的组成员身份更改 Active Directory 用户属性
- python-3.x - 如何从 PySpark UDF 中引发的 Py4JJavaError 中获取原始 Python 错误
- postgresql - 如何优化批量插入?
- hibernate - Hibernate CrudRepository 本机查询不使用 to_timestamp 函数返回结果
- c# - 如何知道是否有来自 Windows 服务的交互式会话处于活动状态?
- python - 浏览全局 file_name 变量中的图像后 imread 出错
- javascript - IE>10浏览器通过js获取上一个URL
- javascript - socket.io 在 node.js 中等待响应