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.

How It Works<br />

As you can see, we have the same two rows that we would have had with an INNER JOIN clause. Those<br />

are then followed by the three Address records that aren’t matched with anything in either table. Last,<br />

but not least, we have the one record from the Vendors table that wasn’t matched with anything.<br />

Again, use a FULL JOIN when you want all records from both sides of the JOIN — matched where possible,<br />

but included even if there is no match.<br />

CROSS JOINs<br />

CROSS JOINs are very strange critters indeed. A CROSS JOIN differs from other JOINs in that there is no<br />

ON operator and that it joins every record on one side of the JOIN with every record on the other side of<br />

the JOIN. In short, you wind up with a Cartesian product of all the records on both sides of the JOIN.<br />

The syntax is the same as any other JOIN, except that it uses the keyword CROSS (instead of INNER,<br />

OUTER, or FULL) and that it has no ON operator. Here’s a quick example:<br />

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

FROM Vendors v<br />

CROSS JOIN Address a<br />

Think back now — we had three records in the Vendors table and five records in the Address table. If<br />

we’re going to match every record in the Vendors table with every record in the Address table, then we<br />

should end up with 3 * 5 = 15 records in our CROSS JOIN:<br />

VendorName Address<br />

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

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

Don’s Database Design Shop 567 Main St.<br />

Don’s Database Design Shop 999 1st St.<br />

Don’s Database Design Shop 1212 Smith Ave<br />

Don’s Database Design Shop 364 Westin<br />

Dave’s Data 1234 Anywhere<br />

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

Dave’s Data 999 1st St.<br />

Dave’s Data 1212 Smith Ave<br />

Dave’s Data 364 Westin<br />

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

The <strong>SQL</strong> Sequel 567 Main St.<br />

The <strong>SQL</strong> Sequel 999 1st St.<br />

The <strong>SQL</strong> Sequel 1212 Smith Ave<br />

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

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

Indeed, that’s exactly what we get.<br />

Chapter 4: JOINs<br />

103

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

Saved successfully!

Ooh no, something went wrong!