-
-
Save nvquanghuy/afd995d2cd4174c759e35120cb420942 to your computer and use it in GitHub Desktop.
CTE and Subquery, MySQL vs Postgres. Example of self-join.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# MySQL | |
select | |
E1.id, | |
E1.full_name, | |
E2.id as supervisor_id | |
E2.full_name as supervisor_full_name | |
from ( | |
select | |
id, | |
first_name || ' ' || last_name as full_name, | |
supervisor_id | |
from people | |
where person_type = 'employed' | |
) E1 | |
left join ( | |
select | |
id, | |
first_name || ' ' || last_name as full_name, | |
supervisor_id | |
from people | |
where person_type = 'employed' | |
) E2 ON E1.supervisor_id = E2.id |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Compare the above with Postgres | |
with employees as ( | |
select | |
id, | |
first_name || ' ' || last_name as full_name, | |
supervisor_id | |
from people | |
where person_type = 'employed' | |
) | |
select | |
E1.id, | |
E1.full_name, | |
E2.id as supervisor_id | |
E2.full_name as supervisor_full_name | |
from employees E1 | |
left join employees E2 ON E1.supervisor_id = E2.id |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
MySQL: just create temporary table instead WITH and use it