20.07.2013 Views

Beginning SQL

Beginning SQL

Beginning SQL

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.

The error wording depends on the database system you’re using, but the overall message is the same:<br />

More than one value — can’t do that with a subquery!<br />

An alternative to using a literal value would be to link the inner query to the outer query, so long as the<br />

result of the inner query produces only one row. For example, the following query shows the CategoryId<br />

from the FavCategory table, and in the subquery, it shows FirstName from the MemberDetails table. The<br />

MemberId in the subquery is linked to the FavCategory table’s MemberId for each row in the outer<br />

query — thereby ensuring that the subquery returns only one row, as MemberIds are unique in the<br />

MemberDetails table:<br />

SELECT CategoryId,<br />

(SELECT FirstName FROM MemberDetails WHERE MemberId = FavCategory.MemberId)<br />

FROM FavCategory;<br />

The results of executing this query are as follows:<br />

CategoryId FirstName<br />

1 John<br />

1 Susie<br />

1 Stuart<br />

2 Katie<br />

2 Doris<br />

3 Susie<br />

3 Jamie<br />

3 William<br />

4 Katie<br />

4 Jenny<br />

4 Jamie<br />

4 Stuart<br />

5 Steve<br />

5 Jamie<br />

5 William<br />

6 Susie<br />

6 Stuart<br />

6 Doris<br />

7 Steve<br />

7 Jenny<br />

7 Stuart<br />

Queries within Queries<br />

239

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

Saved successfully!

Ooh no, something went wrong!