17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Just two records are returned:<br />

VendorID AddressID<br />

-------- -------------<br />

1 1<br />

2 3<br />

(2 row(s) affected)<br />

We know, therefore, that our OUTER JOIN is working. Since there are only two records in the VendorAddress<br />

table and three vendors are returned, we must be returning at least one row from the Vendors table that<br />

didn’t have a matching record in the VendorAddress table. While we’re here, we’ll just verify that by<br />

briefly adding one more column back to our vendors query:<br />

SELECT v.VendorName, va.VendorID<br />

FROM Vendors v<br />

LEFT OUTER JOIN VendorAddress va<br />

ON v.VendorID = va.VendorID<br />

Sure enough, we wind up with a NULL in the VendorID column from the VendorAddress table:<br />

VendorName VendorID<br />

-------------------- --------------<br />

Don’s Database Design Shop 1<br />

Dave’s Data 2<br />

The <strong>SQL</strong> Sequel NULL<br />

(3 row(s) affected)<br />

The vendor named “The <strong>SQL</strong> Sequel” would not have been returned if we were using an INNER or<br />

RIGHT JOIN. Our use of a LEFT JOIN has ensured that we get all vendors in our query result.<br />

Now that we’ve tested things out a bit, let’s return to our original query and then add in the second<br />

JOIN to get the actual address information. Because we don’t care if we get all addresses, no special<br />

JOIN is required — at least, it doesn’t appear that way at first . . .<br />

SELECT v.VendorName, a.Address<br />

FROM Vendors v<br />

LEFT OUTER JOIN VendorAddress va<br />

ON v.VendorID = va.VendorID<br />

JOIN Address a<br />

ON va.AddressID = a.AddressID<br />

We get back the address information as expected, but there’s a problem:<br />

VendorName Address<br />

--------------------------- ---------------<br />

Don’s Database Design Shop 1234 Anywhere<br />

Dave’s Data 567 Main St.<br />

(2 row(s) affected)<br />

Chapter 4: JOINs<br />

99

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!