首页 > 解决方案 > SQL Server内部连接查询从多对多关系表

问题描述

我是 SQL 编程新手,遇到以下问题。

我有 3 张桌子:

  1. tblMaschine (id PK, type as char(5))
  2. tblUse (id PK, typeOfUse varchar(255))
  3. 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类型。tblmaschinemaschineUse

我正在使用这个查询,但它什么也不返回:

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';

我究竟做错了什么?

标签: sqlsql-servertsqljoin

解决方案


一个选项使用聚合:

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)

推荐阅读