MySQL:从多对多表中获取条目

时间:2016-02-08 08:10:05

标签: mysql sql database

我有一个下表,我想选择应该具有所有提到的值的记录。例如 选择CompanyID,其中应包含所有三个ProviderID 200,300,400。因此,运行查询应该返回CompanyID 2.与IN相反。提前谢谢!

CompanyID      |        ProviderID
--------------------------------------
    1                 100
    2                 200
    3                 500
    4                 600
    2                 300
    2                 400
    7                 100

1 个答案:

答案 0 :(得分:1)

执行GROUP BY,仅选择包含3个所需EmployeeID值中的任何一行的行。使用HAVING确保获得3个不同的EmployeeID值。

select CompanyID
from tablename
where EmployeeID IN (200, 300, 400)
group by CompanyID
having count(distinct EmployeeID) = 3

另一种方法是双自联接,每个EmployeeID一个。但是,这不太灵活:

select distinct t1.CompanyID
from (select CompanyID from tablename where EmployeeID = 200) t1
join (select CompanyID from tablename where EmployeeID = 300) t2
    on t1.CompanyID = t2.CompanyID 
join (select CompanyID from tablename where EmployeeID = 400) t3
    on t2.CompanyID = t3.CompanyID