我们如何连接 MySQL 中的公用表?

How can we join common tables in MySQL?

我在 Postgres 中有一个复杂的查询,我正试图在 MySQL 中进行转换。 Postgres 查询具有三个链式查询。前两个创建两个公共 tables,最后一个查询对这两个公共 tables 进行连接。查询的简化版本看起来像这样。有没有办法在 MySQL 中加入这两个常见的 table?我需要针对 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

第三个查询应该在 table1.y_id = table2.year_id.

上连接 table1 和 table2

对每个查询的作用有一个高层次的了解:

  1. 查询 1 从 master table(Say, table 1) 获取数据并存储 根据某些条件
  2. ,它在一个常见的 table 中
  3. 查询 2 根据用户指定的列对查询 1 中获得的行进行分组和排序,并将其限制在顶部 'N'
  4. 查询 3 returns 仅这 N 个唯一 ID(从 table 2 获得)的所有详细信息(在 table 1 上)通过在 table1.id = 上执行连接
    table2.id

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