I have a complex query in Postgres which I am trying to convert in MySQL. The Postgres query has three chained queries. The first two create two common tables and the final query does a join on these two common tables. A simplified version of the query looks something like this . Is there a way to join these two common tables in MySQL ? I need the query to run for 5.6,5.7 and 8.0 so the new feature for CTE in 8.0 is not a solution.
(Select table1.y_id as year_id,
SUM(table1.total_weight) AS metric_value
from (SELECT student_name,y_id,total_weight from student_metrics where y_id>10 ) table1
group by year_id
order by metric_value DESC
limit by 5
)table2
The third query should do a join of table1 and table2 on table1.y_id = table2.year_id.
To give a high level idea of what each of the query does:
You could simply repeat the table1
subquery:
select
table1.*
from
(select student_name,y_id,total_weight from student_metrics where y_id>10) as table1
inner join (
select tbl1.y_id as year_id,
sum(tbl1.total_weight) as metric_value
from
(select student_name,y_id,total_weight from student_metrics where y_id>10 ) as tbl1
group by tbl1.y_id
order by sum(tbl1.total_weight) desc
limit by 5
) as table2 on table1.y_id = table2.year_id;