MySQL 4.1 introduced subqueries.
Any SQL statement is a query, but this term generally refers to a SELECT statement.
There are two tables, one is the language table and the other is the movie table:
select movies whose language is English:
SELECT title
FROM film
WHERE language_id IN (SELECT language_id
FROM language
WHERE name = 'English');
There is no limit to the number of subqueries that can be nested, but due to performance limitations, too many subqueries cannot be nested.
The IN in the above example can also be replaced by an equal sign.
Subqueries are not always the most effective way to perform this type of data retrieval, and performance will be poor.
The subquery always runs from the inside to the outside.
Subqueries can also be used as calculated fields. The following example calculates the number of movies in each language:
SELECT language_id,
name,
(SELECT COUNT(*)
FROM film
WHERE film.language_id = language.language_id) AS num
FROM language;
Run it: The
above example shows only English movies in the film table. The subquery in the above example is executed six times because there are six languages.
If the fully qualified table name is not used in the subquery:
At this time, MySQL assumes that the language_id in the film table is compared with itself, and the subquery always returns all values.
When debugging the nested sub-query SQL statement, you can run the sub-query first to see if it meets the expectations, and then join the sub-queries after it meets the requirements, which can save the time to find out why the query is abnormal.