Site icon TestingDocs.com

MySQL Convert Subquery to Join

Overview

In this tutorial, we will learn steps to convert subquery to Join with a example. A MySQL subquery statement in many cases can be converted to a Join statement.

A join is sometimes more efficient than a subquery, so if a SELECT written as a subquery takes a long time to execute, we can try converting it as a join to see if it performs better. Specifically, a subquery that finds matches between tables often can be rewritten as an inner join or outer join.

Example

In this example, we will use the Country and the CountryLanguage tables from the world MySQL database.

 

 

For example, an IN subquery that identifies countries for which languages are listed in the CountryLanguage table looks like this:

mysql> SELECT Name FROM Country
-> WHERE Code IN
-> (SELECT Countryside
-> FROM CountryLanguage);

 

To convert this subquery into an inner join, do the following:

 

Move the CountryLanguage table named in the subquery to the FROM clause.

The WHERE clause compares the CODE column to the country codes returned from the subquery. Convert the IN expression to an explicit direct comparison between the country code columns of the two tables.

These changes result in the following INNER join:

mysql> SELECT Name FROM Country, CountryLanguage
-> WHERE Code=CountryCode;

 

 

Notice that the output is not quite the same as that from the subquery, which lists each matched country just once. To list each name once, as in the subquery, just add  the DISTINCT keyword to the join statement as follows:

mysql> SELECT DISTINCT Name FROM Country, CountryLanguage
              -> WHERE Code=CountryCode;

 

Note that the subqueries using aggregate functions cannot be converted to joins.

MySQL Tutorials

MySQL Tutorials on this website:

https://www.testingdocs.com/mysql-tutorials-for-beginners/

For more information on MySQL Database:

https://www.mysql.com/

Exit mobile version