我有一些冲突观点:
首先,我创建一些基本视图以进行低级过滤器
CREATE OR REPLACE VIEW view1 AS
SELECT * FROM table1 WHERE conditions
CREATE OR REPLACE VIEW view2 AS
SELECT * FROM table2 WHERE conditions
...
然后,我分别加入他们的行列。连接关系看起来像一个表到多个表,因此我为每个表-表连接创建一个视图。
CREATE OR REPLACE VIEW join1_view1 AS
SELECT * FROM view1 JOIN view2 ON view1.entity_type = 'View2' AND view1.entity_id = view2.id WHERE conditions
CREATE OR REPLACE VIEW join1_view2 AS
SELECT * FROM view1 JOIN view3 ON view1.entity_type = 'View3' AND view1.entity_id = view3.id WHERE conditions
CREATE OR REPLACE VIEW join2_view1 AS
SELECT * FROM view1 JOIN view4 ON view1.assigned_type = 'View4' AND view1.assigned_id = view4.id WHERE conditions
CREATE OR REPLACE VIEW join2_view2 AS
SELECT * FROM view1 JOIN view5 ON view1.assigned_type = 'View5' AND view1.assigned_id = view5.id WHERE conditions
...
然后我用Union来组合它们。
CREATE OR REPLACE VIEW union1 AS
SELECT * FROM join1_view1
UNION
SELECT * FROM join1_view2
CREATE OR REPLACE VIEW union2 AS
SELECT * FROM join2_view1
UNION
SELECT * FROM join2_view2
现在一切都很好。但是在下一步,我将加入这两个联合视图。
CREATE OR REPLACE VIEW join_union AS
SELECT * FRON union1 INNER JOIN union2 ON union1.id = union2.id
然后我发现如果我设置了不同的限制,查询时间就会有所不同。
没有限制:
SELECT * FROM join_union
需要4秒。限制100:
SELECT * FROM join_union LIMIT 100
需要5秒。限制500需要10秒。 LIMIT 1000需要16秒。
还没有结束。令人惊讶的是,经过1000次后,LIMIT 2000需要1秒。 LIMIT 100,000(实际上总共有20,000条记录)需要3秒。
曲线如下:
最长时间发生在LIMIT 1325
在这种情况下,我执行了EXPLAIN(ANALYSE,BUFFERS),我得到了以下计划: