[SQL]不知道1

表结构,companyid是公司名,productid是产品号,说明每个公司生产多少种产品。

companyid   productid  
A                1
A                2 
B                1
B                2 
B                3
C                1 
D                1
D                2 
D                5


要求:取出所有生产的产品包含公司A所生产产品的所有公司名。
例如,公司A生产1,2,那么产品中至少包含1,2(可以更多)的公司名被选出,即A,B,D

求一句实现的sql语句。

方案一

select  a.companyid  
from 你的表 a 
where exists  (select 1 from 你的表 b where b.companyid='A' and a.productid =b.productid  )
group by a.companyid 
having count(a.productid)>=2 

方案二

select companyid from T A 
where not exists
(select 1 from T where companyid='A' and productid not in 
(select productid from T where companyid = A.companyid))
原文地址:https://www.cnblogs.com/beeone/p/3622296.html