[英]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.