如何连接mysql中的公共表?

qzwqbdag  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(372)

我在postgres中有一个复杂的查询,我正试图在mysql中转换它。postgres查询有三个链式查询。前两个查询创建两个公共表,最后一个查询对这两个公共表进行联接。查询的简化版本如下所示。在mysql中有没有连接这两个常用表的方法?我需要查询运行5.6,5.7和8.0,所以8.0中cte的新特性不是一个解决方案。

(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

第三个查询应该连接上的表1和表2 table1.y_id = table2.year_id. 要从较高的层次了解每个查询的作用,请执行以下操作:
查询1从主表(比如表1)获取数据,并根据某些条件将其存储在公共表中
query 2根据用户指定的列对查询1中获得的行进行分组和排序,并将其限制为top'n'
查询3通过对table1.id执行连接,只返回这n个唯一id(从表2中获得)的所有详细信息(在表1上)=
表2.id

ntjbwcob

ntjbwcob1#

你可以简单地重复 table1 子查询:

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;

相关问题