【问题标题】:Excluding results in one table from a SELECT * in another? [duplicate]从另一个表中的 SELECT * 中排除一个表中的结果? [复制]
【发布时间】:2012-08-12 00:53:43
【问题描述】:

可能重复:
MySQL SELECT results from 1 table, but exclude results depending on another table?

我希望我不是在问已经回答的问题..没有看到。看起来很简单,但我无法让它工作。

我有两个表:Unit 和 Lease。

我想要单元表中所有打开的单元(建筑物和单元单元编号)的列表,不包括租赁表中 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));

【问题讨论】:

标签: mysql


【解决方案1】:

试试这个:

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

在其他数据库引擎中,您会使用“not in”。但是,这在 mysql 中优化得更好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2011-01-31
    • 1970-01-01
    相关资源
    最近更新 更多