我有一个“主”表和多个关联表(让我们调用T1,T2等...)。所有相关表都与N-1中的MAin相关。现在我有一个统计查询来收集关联表的聚合信息。这是查询示例:
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 ... )
正如您所看到的,我一直在使用单独的GROUP BY子查询,我将所有内容与一组LEFT JOIN连接在一起。到目前为止一切正常,但......
我需要根据该查询创建一个VIEW,并且您可能知道,在MySQL VIEW中不可能使用子查询。所以问题是:如何在不使用子查询的情况下重写这样的查询?
注意:我知道我可以为每个子查询使用多个子VIEW。但这是我宁愿避免的一种选择。
答案 0 :(得分:0)
为每个子查询创建分隔视图,然后可以直接调用视图。它会工作。 或使用mysql workbench连接mysql DB。并从mysqlworkbench运行create view脚本。它会起作用。
示例:
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
.... ....