Analyzing subqueries
Another way of joining the tables is available in MySQL. It consists of using the output of a query directly in another query.
Use the world_simple
table as an example again and look at the following query:
SELECT Name FROM city WHERE CountryCode=( SELECT Code FROM country WHERE Name='Romania' );
This query produces the following output:
The preceding query is essentially running this command:
SELECT Code FROM country WHERE Name='Romania';
It then saves the result and runs the following query:
SELECT Name FROM city WHERE CountryCode=<saved_result>
So, to use a subquery, you place the query inside (
and )
and place it where you want to see the output. This can be in the WHERE
part of the query, but also the SELECT
part and most other places.
Dependent subqueries
In the previous example, the two queries were independent, but in some...