20.07.2013 Views

Beginning SQL

Beginning SQL

Beginning SQL

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

SELECT * FROM FavCategory<br />

Figure 3-3<br />

CategoryId<br />

1<br />

1<br />

1<br />

2<br />

2<br />

3<br />

2<br />

6<br />

1<br />

MemberId<br />

3<br />

5<br />

10<br />

1<br />

3<br />

3<br />

14<br />

14<br />

3<br />

On FavCategory.CategoryId = Category.CategoryId<br />

FavCategory Table<br />

CategoryId MemberId<br />

1 3<br />

1 5<br />

1 10<br />

2 1<br />

2 3<br />

3 3<br />

4<br />

6<br />

3<br />

5<br />

2<br />

0<br />

12<br />

12<br />

13<br />

13<br />

14<br />

14<br />

Category Table<br />

CategoryId Category<br />

1 Thriller<br />

1 Thriller<br />

1 Thriller<br />

2 Romance<br />

2 Romance<br />

3 Horror<br />

SELECT * FROM Category<br />

CategoryId<br />

1<br />

2<br />

3<br />

4<br />

5<br />

6<br />

Category<br />

Thriller<br />

Romance<br />

Horror<br />

War<br />

Sci-fi<br />

Historical<br />

The circle on the left represents the set of records from the FavCategory table. Because the set isn’t<br />

filtered (for example, with a WHERE clause), it includes all the FavCategory records, though the diagram<br />

shows only a handful. The circle on the right is the set of records from the Category table, again unfiltered<br />

to include all the records. In the center is the overlap between the two sets, defined by the ON<br />

clause in the INNER JOIN. The results set in the overlap is the final results obtained. It includes all<br />

the records from the other two results sets, where there is a matching CategoryId in each table for<br />

each record. As it happens, the CategoryId in every record in the FavCategory table finds a matching<br />

CategoryId in the CategoryId column, so every record from the FavCategory table is included. The<br />

<strong>SQL</strong> statement selects only two columns, Category and MemberId, to be returned in the results.<br />

However, when the database performs the join, all the fields listed in the ON statement are also<br />

considered.<br />

In order to demonstrate that only records with matching CategoryId’s in both tables are included in the<br />

joined results set, add another record to the Category table. First, though, here are the results without<br />

the new record added:<br />

4<br />

6<br />

3<br />

5<br />

2<br />

6<br />

War<br />

Historical<br />

Horror<br />

Sci-fi<br />

Romance<br />

Historical<br />

Extracting Information<br />

103

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

Saved successfully!

Ooh no, something went wrong!