Left Join Lateral and array aggregates

你说的曾经没有我的故事 提交于 2019-12-06 04:59:42
Erwin Brandstetter

As @Denis already commented: no need for LATERAL. Also, your subquery selected the wrong column. This works:

SELECT t1.t1_id, t1.t1_data, t2_ids
FROM   t1
LEFT   JOIN (
    SELECT t1_id, array_agg(t2_id) AS t2_ids
    FROM   t1_t2_rel
    GROUP  BY 1
    ) sub USING (t1_id);

-SQL fiddle.

Performance and testing

Concerning the ensuing sequential scan you mention: If you query the whole table, a sequential scan is often faster. Depends on the version you are running, your hardware, your settings and statistics of cardinalities and distribution of your data. Experiment with selective WHERE clauses like WHERE t1.t1_id < 1000 or WHERE t1.t1_id = 1000 and combine with planner settings to learn about choices:

SET enable_seqscan = off;
SET enable_indexscan = off;

To reset:

RESET enable_seqscan;
RESET enable_indexscan;

Only in your local session, mind you! This related answer on dba.SE has more instructions.
Of course, your setting may be off, too:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!