简体   繁体   English

MySQL中没有子查询的多重表聚集

[英]Multiples tables aggragation without subqueries in MySQL

I have a "Main" table and multiple associated tables (let's call then T1, T2, etc...). 我有一个“主”表和多个关联的表(让我们先调用,然后再调用T1,T2等)。 All associated tables are related to MAin in N-1. 所有关联的表都与N-1中的MAin有关。 Now I have a statistic query that collect aggregate informations on the associated tables. 现在,我有了一个统计查询,该查询收集关联表上的汇总信息。 Here is the query example: 这是查询示例:

SELECT *
    Main.*,
    Sub1.*,
    Sub2.*,
    ...
FROM Main
LEFT JOIN (
    SELECT T1.main_id, SUM(T1.col1) as stat1, AVG(T2.col2) as stat2
    FROM T1
    GROUP T1.main_id
) Sub1 ON Sub1.main_id = Main.id
LEFT JOIN (
    SELECT T2.main_id, COUNT|AVG|SUM
    FROM T2
    GROUP T2.main_id
) Sub2 ON Sub2.main_id = Main.id
LEFT JOIN ( T3 ... )

As you can see, I have been using separate GROUP BY subqueries and I join everything together with a set of LEFT JOIN. 如您所见,我一直在使用单独的GROUP BY子查询,并将所有内容与一组LEFT JOIN连接在一起。 Everything is working fine until now, but... 到现在为止一切都很好,但是...

I need to create a VIEW based on that query, and as you maybe know, it's not possible to use subqueries in MySQL VIEWs. 我需要基于该查询创建一个VIEW,并且您可能知道,无法在MySQL VIEW中使用子查询。 So the question is: How to rewrite such query without using subqueries? 所以问题是:如何在不使用子查询的情况下重写此类查询?

Note: I know that I can use several sub VIEWs for each subquery. 注意:我知道我可以为每个子查询使用多个子VIEW。 But this is an option I prefer to avoid. 但这是我更希望避免的选择。

Create seperated view for each subquery then you can call directly view. 为每个子查询创建单独的视图,然后可以直接调用视图。 it will work. 它会工作。 or Use mysql workbench to connect mysql DB. 或使用mysql工作台连接mysql DB。 and run create view script from mysqlworkbench. 并从mysqlworkbench运行create view脚本。 It will work. 它会工作。

Example: 例:

create or replace view SUB1 as SELECT T1.main_id, SUM(T1.col1) as stat1, AVG(T2.col2) as stat2
    FROM T1
    GROUP T1.main_id;



create or replace view SUB2 as SELECT T2.main_id, COUNT|AVG|SUM
    FROM T2
    GROUP T2.main_id;

SELECT *
    Main.*,
    Sub1.*,
    Sub2.*,
    ...
FROM Main
LEFT JOIN Sub1 ON Sub1.main_id = Main.id
LEFT JOIN SUB2 on Sub2.main_id = Main.id

.... .... .... ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM