我在 Postgres 中有一个复杂的查询,我试图在 MySQL 中转换它。 Postgres 查询具有三个链式查询。前两个创建两个公用表,最后一个查询对这两个公用表进行联接。查询的简化版本如下所示。有没有办法在 MySQL 中连接这两个公共(public)表?我需要在 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)中获取数据并存储 它在基于某些条件的通用表中
- 查询 2 根据用户指定的列对查询 1 中获取的行进行分组和排序,并将其限制为前“N”
- 查询 3 通过在 table1.id 上执行联接,仅返回这 N 个唯一 ID(从表 2 获取)的所有详细信息(在表 1 上)=
表2.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;
关于mysql - 我们如何连接 MySQL 中的公共(public)表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53272801/