Tuesday, March 20, 2012

Query to only display information from one table where the foreign key doesnt exist in the

I want to make a query, stored procedure, or whatever which will only display the primary key where there does no exist a foreign key in linked table.

For example. If I had two tables with a one to many relationship.

A [Computer] has one or more [Hard Drives].

I want to select only those computers which do not have a Hard Drive(s) associated with them. That is, show all computers where the Computer_ID field in the [Hard Drives] table does not exist.

This seems simple but I'm drawing a blank here.

SELECT * FROM Computer where ComputerId NOT IN (SELECT ComputerId FROM [Hard Drives])

No comments:

Post a Comment