在 postgres 的第一个 table 左加入预过滤

Left join pre-filtering on first table in postgres

我想运行查询以获取用户相册 ID、名称和相册中的图片数量。此查询有效:

SELECT album.id, album.name, count(pictures.*)
FROM album
LEFT JOIN pictures
    ON (pictures.album_id=album.id)
WHERE album.owner = ?
GROUP BY album.id;

我有很多图片和很多相册,但是在筛选我感兴趣的用户之前加入 运行ning。

我看到其他答案根据第二个 table 的值在连接内部进行过滤,但我想过滤第二个 [=19= 中未包含的 album.owner ].如何在加入之前进行过滤? (效率高吗?我会破坏索引吗?)

对于此查询:

SELECT a.id, a.name, count(p.album_id)
FROM album a LEFT JOIN
     pictures p
    ON p.album_id = a.id
WHERE a.owner = ?
GROUP BY a.id;

您想要 album(owner, id, name) 上的索引。这应该会加快您的查询速度。

但是,如果这样写可能会更快:

SELECT a.id, a.name,
       (SELECT count(*)
        FROM pictures p
        WHERE p.album_id = a.id
       )
FROM album a 
WHERE a.owner = ?

这里你想要上面的索引和pictures(album_id)上的索引。