代码之家  ›  专栏  ›  技术社区  ›  user5566364

如何在MySQL中连接公共表?

  •  0
  • user5566364  · 技术社区  · 6 年前

    我在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从主表(比如表1)获取数据并存储
    2. Query 2根据用户指定的列对查询1中获得的行进行分组和排序,并将其限制为top'N'
    3. 查询3通过对table1.id执行连接,只返回这N个唯一id(从表2中获得)的所有详细信息(在表1上)=
      表2.id
    1 回复  |  直到 6 年前
        1
  •  1
  •   rd_nielsen    6 年前

    你可以简单地重复 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;