2012-08-15 80 views
-5

可能重複:
MySQL SELECT results from 1 table, but exclude results depending on another table?從另一個SELECT *中排除一個表中的結果?

我希望我不要求什麼已經answered..didn't看到一個。似乎很簡單,但我無法讓它工作。

我有兩個表:單位和租賃。

我想要列出所有打開的單位(建築物和單位unitnumber)的一切,從單位表中排除租賃表中的那些在enddate字段中爲空的單位。

結構表(我刪除沒有必要在這個例子中其他領域:

CREATE TABLE Unit(
    UnitKey  Int NOT NULL AUTO_INCREMENT, 
    UnitNumber Char(5) NOT NULL, 
    BuildingKey Int  NOT NULL, 
    CONSTRAINT UNIT_PK PRIMARY KEY(UnitKey), 
    CONSTRAINT UNIT_BLDG_FK  FOREIGN KEY(BuildingKey) 
        REFERENCES Building(BuildingKey)); 

CREATE TABLE Lease(
    LeaseKey Int     NOT NULL AUTO_INCREMENT, 
    UnitKey Int     NOT NULL, 
    EndDate  Date     NULL, 
    CONSTRAINT LEASE_PK    PRIMARY KEY(LeaseKey), 
    CONSTRAINT  LEASE_UNIT_FK FOREIGN KEY(UnitKey) REFERENCES Unit(UnitKey)); 
+2

類似於:http://stackoverflow.com/questions/4186242/sql-select-all-unique-values-in-table-a-which-are-not-in-table- b和http://stackoverflow.com/questions/4660871/mysql-se lect-all-items-from-table-a-if-not-exist-in-table -b – Charx 2012-08-15 17:37:23

+2

你的問題已經被回答了很多次:http://stackoverflow.com/questions/2862778/mysql-select-results -from-1-table-but-exclude-results-depends-on-another-tabl?rq = 1 http://stackoverflow.com/questions/7596073/select-from-one-table-where-not-in-另一個?rq = 1 http://stackoverflow.com/questions/10255266/select-users-from-one-table-only-if-not-in-another?rq=1 – Jocelyn 2012-08-15 17:41:46

回答

1

試試這個:

select u.* 
from units u 
where not exists (select 1 from lease l where l.unitkey = u.unitkey and l.enddate is null) 

在其他的數據庫引擎,你會用「不」然而,。這在mysql中優化得更好。

相關問題