
The MySQL Workshop
By :

If a query is joining multiple tables and also has subqueries, then things might start to look a little complex. But luckily, there is a way to do this that's easier to understand. This is called Common Table Expressions (CTEs). This is also known as WITH
because that's the keyword we have to use for this. Consider the following expression:
WITH city_in_romania AS ( SELECT ci.Name, ci.CountryCode, co.Name AS CountryName FROM city ci INNER JOIN country co ON ci.CountryCode=co.Code AND co.Name='Romania' ) SELECT * FROM city_in_romania;
This produces the following output:
Figure 5.22 – SELECT with CTE
In the first few lines, we define city_in_romania
as a new table that's only available for this query. It is made by a join of the country
and city
tables and then filtered on the country
name. Then we can use this new table in the second part of the query. We can define multiple...