Site icon TestingDocs.com

MySQL Convert Joins to Subqueries

Overview

In this tutorial, we will learn steps to Convert Joins to Subqueries with an example. We can replace a join statement with a subquery. Sometimes its easy to construct a subquery rather than using a join. However, subqueries will normally run slower than join statements.

Steps to convert a Subquery to a JOIN statement:

https://www.testingdocs.com/mysql-convert-subquery-to-join/

Example

In this example, we will use the Country and the CountryLanguage tables from the world MySQL database. The following query shows the JOIN query to know the languages spoken in a particular continent, for example, North America.

JOIN Statement

mysql> SELECT DISTINCT language
-> FROM Country AS c
-> JOIN CountryLanguage AS cl
-> ON cl.CountryCode=c.Code
-> WHERE c.Continent= ‘North America’;


+——————+
| language |
+——————+
| Dutch |
| English |
| Papiamento |
| Spanish |
| Creole English |
| Creole French |
| Garifuna |
| Maya Languages |
| Bajan |
| Chinese |
| Eskimo Languages |
| French |
| German |
| Italian |
| Polish |
| Portuguese |
| Punjabi |
| Ukrainian |
| Chibcha |
| Danish |
| Greenlandic |
| Cakchiquel |
| Kekchí |
| Mam |
| Quiché |
| Miskito |
| Haiti Creole |
| Hindi |
| Mixtec |
| Náhuatl |
| Otomí |
| Yucatec |
| Zapotec |
| Sumo |
| Arabic |
| Cuna |
| Embera |
| Guaymí |
| Nahua |
| Japanese |
| Korean |
| Tagalog |
| Vietnamese |
+——————+
43 rows in set (0.00 sec)

Subquery

Now let’s convert this to  subquery as shown below. The following subquery displays the same result as the above JOIN statement.

mysql> SELECT DISTINCT Language
             -> FROM CountryLanguage
             -> WHERE CountryCode IN
             -> (SELECT Code FROM Country WHERE Continent=’North America’);
+——————+
| Language |
+——————+
| Dutch |
| English |
| Papiamento |
| Spanish |
| Creole English |
| Creole French |
| Garifuna |
| Maya Languages |
| Bajan |
| Chinese |
| Eskimo Languages |
| French |
| German |
| Italian |
| Polish |
| Portuguese |
| Punjabi |
| Ukrainian |
| Chibcha |
| Danish |
| Greenlandic |
| Cakchiquel |
| Kekchí |
| Mam |
| Quiché |
| Miskito |
| Haiti Creole |
| Hindi |
| Mixtec |
| Náhuatl |
| Otomí |
| Yucatec |
| Zapotec |
| Sumo |
| Arabic |
| Cuna |
| Embera |
| Guaymí |
| Nahua |
| Japanese |
| Korean |
| Tagalog |
| Vietnamese |
+——————+
43 rows in set (0.01 sec)

 

 

 

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