[英]Select from table where id is not in another
我想选择所有不属于某个公司的飞机。 在这种情况下,我有三个表: Planes
, Companies
和CompanyPlanes
。
这是我的查询:
SELECT *
FROM planes p,
companyplanes cp,
companies c
WHERE c.id = ?
AND cp.idCompany != c.id
AND (cp.idPlane = p.id OR p.id NOT IN (SELECT idPlane FROM companyplanes))
ORDER BY name ASC
但是这个查询什么也没返回! 这是怎么了
例:
| Plane |
---------
id | name
---------
1 | p1
2 | p2
3 | p3
|Company|
---------
id | name
---------
1 | c1
2 | c2
| companyPlanes |
------------------------
id | idCompany | idPlane
------------------------
1 | 1 | 1
2 | 1 | 2
3 | 2 | 2
如果要获取不属于公司c2
的飞机,则结果应为:p1,p3。
更新答案
我们可以通过以下方式获得结果
获取意外公司的所有飞机
SELECT idplane from CompanyPlanes WHERE idCompany = ?
获得所有飞机,而没有那些意外公司的飞机
SELECT * FROM Planes WHERE id NOT IN ( SELECT idplane from CompanyPlanes WHERE idCompany = ? )
你并不需要join
与Company
的表,你已经得到idCompany
从CompanyPlanes
表。
内部联接要求查询从在公司平面中具有相应行的平面返回行,但是子选择不包括在公司平面中具有相应记录的任何行。
假设您要从公司飞机中没有记录的飞机中获取记录,那么为什么还要从公司中选择呢?
Select p.*
From planes p
Left join
Companyplanes do
On p.id=cp.idplane
Where cp.idplane is null;
如果我以正确的方式理解您的问题,这就是您所要寻找的。
select p.*
from planes p
join companyplanes cp on cp.idPlane=p.id
join companies c on c.id=cp.idCompany
where c.id != ?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.