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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 4: JOINs<br />

98<br />

vendor. We’re going to go ahead and start aliasing from the beginning, since we will want to do this in<br />

the end:<br />

USE Chapter4DB<br />

SELECT v.VendorName<br />

FROM Vendors v<br />

This yields a scant three records:<br />

VendorName<br />

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

Don’s Database Design Shop<br />

Dave’s Data<br />

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

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

These are the names of every vendor that we have at this time. Now let’s add in the address information<br />

— there are two issues here. First, we want the query to return every vendor no matter what, so<br />

we’ll make use of an OUTER JOIN. Next, a vendor can have more than one address and vice versa, so the<br />

database design has made use of an associate table. This means that we don’t have anything to directly<br />

join the Vendors and Address tables — we must instead join both of these tables to our linking table,<br />

which is called VendorAddress. Let’s start out with the logical first piece of this join:<br />

SELECT v.VendorName<br />

FROM Vendors v<br />

LEFT OUTER JOIN VendorAddress va<br />

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

Because VendorAddress doesn’t itself have the address information, we’re not including any columns<br />

from that table in our SELECT list. VendorAddress’s sole purpose in life is to be the connection point of a<br />

many-to-many relationship (one vendor can have many addresses and, as we’ve set it up here, an address<br />

can be the home of more than one vendor). Running this, as we expect, gives us the same results as before:<br />

VendorName<br />

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

Don’s Database Design Shop<br />

Dave’s Data<br />

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

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

Let’s take a brief time-out from this particular query to check on the table against which we just joined.<br />

Try selecting all the data from the VendorAddress table:<br />

SELECT *<br />

FROM VendorAddress

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

Saved successfully!

Ooh no, something went wrong!