簡體   English   中英

從ID不在另一個表中選擇

[英]Select from table where id is not in another

我想選擇所有不屬於某個公司的飛機。 在這種情況下,我有三個表: PlanesCompaniesCompanyPlanes

這是我的查詢:

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。

更新答案

我們可以通過以下方式獲得結果

  1. 獲取意外公司的所有飛機

    SELECT idplane from CompanyPlanes WHERE idCompany = ?

  2. 獲得所有飛機,而沒有那些意外公司的飛機

    SELECT * FROM Planes WHERE id NOT IN ( SELECT idplane from CompanyPlanes WHERE idCompany = ? )

你並不需要joinCompany的表,你已經得到idCompanyCompanyPlanes表。

內部聯接要求查詢從在公司平面中具有相應行的平面返回行,但是子選擇不包括在公司平面中具有相應記錄的任何行。

假設您要從公司飛機中沒有記錄的飛機中獲取記錄,那么為什么還要從公司中選擇呢?

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM