[英]Select from table where id is not in another
I want to select all the planes that aren't belong to a certain company. 我想选择所有不属于某个公司的飞机。 I have three tables in this case:
Planes
, Companies
, and CompanyPlanes
. 在这种情况下,我有三个表:
Planes
, Companies
和CompanyPlanes
。
Here is my query: 这是我的查询:
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
But this query returned nothing! 但是这个查询什么也没返回! what is the wrong here?
这是怎么了
example: 例:
| 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
if I want to get the planes that are not belong to the company c2
the result should be: p1, p3. 如果要获取不属于公司
c2
的飞机,则结果应为:p1,p3。
Update Answer 更新答案
We can get the result in following way 我们可以通过以下方式获得结果
Get all planes of the unexpected company 获取意外公司的所有飞机
SELECT idplane from CompanyPlanes WHERE idCompany = ?
Get all planes without those planes of the unexpected company 获得所有飞机,而没有那些意外公司的飞机
SELECT * FROM Planes WHERE id NOT IN ( SELECT idplane from CompanyPlanes WHERE idCompany = ? )
You don't need to join
with Company
table as you already get idCompany
from CompanyPlanes
table. 你并不需要
join
与Company
的表,你已经得到idCompany
从CompanyPlanes
表。
The inner join requires that the query return rows from planes which have a corresponding row in companyplanes but the subselect excludes any rows which have corresponding records in companyplanes. 内部联接要求查询从在公司平面中具有相应行的平面返回行,但是子选择不包括在公司平面中具有相应记录的任何行。
Assuming that you want the records from planes which don't have a record in companyplanes, then why are you also selecting from companies? 假设您要从公司飞机中没有记录的飞机中获取记录,那么为什么还要从公司中选择呢?
Select p.*
From planes p
Left join
Companyplanes do
On p.id=cp.idplane
Where cp.idplane is null;
If I understand your question the right way, this is what you might be looking for.. 如果我以正确的方式理解您的问题,这就是您所要寻找的。
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.