-5

Possible Duplicate:
MySQL SELECT results from 1 table, but exclude results depending on another table?

I hope I'm not asking something already answered..didn't see one. Seems simple but I can't get it to work.

I have two tables: Unit and Lease.

I want a list of all open Units (building and unit unitnumber) everything from the unit table excluding those units in the lease table that have a null in the enddate field.

Structure for tables (i removed other fields not necessary for this example:

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

1 Answer 1

1

Try this:

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

In other database engines, you would use "not in". However, this optimizes better in mysql.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.