To query hierarchical relational data in MySQL
, recursive Common Table Expressions (CTEs)
are typically used. However, MySQL did not support recursive CTEs before version 8.0, so in earlier versions, self-joins
are commonly used to handle such queries. Below is an example using a self-join, assuming we have a table employees that contains information about employees and their manager IDs (manager_id).
Create Table and Insert Data
Creating a table named employees
with the following columns:
1 | CREATE TABLE employees ( |
Self-Join
We can search for all employees and their direct reports (subordinates) using a self-join. The following SQL statement will list all employees and their direct manager’s name.
1 | SELECT e1.name AS employee_name, e2.name AS manager_name |
We can also use a self-join to count the number of direct reports for each manager. The following SQL statement will list all managers and the number of their direct reports.
1 | SELECT e1.name AS manager_name, COUNT(e2.id) AS subordinate_count |
Recursive Common Table Expressions (CTEs)
MySQL 8.0 introduced support for recursive CTEs, which allows us to query hierarchical relational data more efficiently. The following SQL statement will list all employees and their direct reports (subordinates) using a recursive CTE.
1 | WITH RECURSIVE subordinates AS ( |
But please note that this method only works for MySQL 8.0
and above, as these versions support recursive CTEs
.