加入子查询的所有结果
Join all results of a subquery
所以我想 LEFT JOIN
至少被多个列之一引用的所有文件:
SELECT
...
FROM
O o
LEFT JOIN binary_stream_value bsv ON o.binary_stream_value_id = bsv.id
LEFT JOIN artwork art ON o.artwork_id = art.id
LEFT JOIN (SELECT f.id FROM file f WHERE f.id = bsv.file_id OR f.id = art.file_id) f ON TRUE
...
失败
ERROR: invalid reference to FROM-clause entry for table "bsv"
LINE 212: ... LEFT JOIN (SELECT f.id FROM file f WHERE f.id = bsv.file_i...
^
HINT: There is an entry for table "bsv", but it cannot be referenced from this part of the query.
诚然,我一半希望这会失败,一半希望我错了。
编写此类查询的正确方法是什么?
你需要一个横向连接来完成你想做的事情:
SELECT
...
FROM
O o
LEFT JOIN binary_stream_value bsv ON o.binary_stream_value_id = bsv.id
LEFT JOIN artwork art ON o.artwork_id = art.id
LEFT JOIN LATERAL (SELECT f.id FROM file f WHERE f.id = bsv.file_id OR f.id = art.file_id) f ON TRUE
...
但是子select并不是真正必要的开头:
SELECT
...
FROM
O o
LEFT JOIN binary_stream_value bsv ON o.binary_stream_value_id = bsv.id
LEFT JOIN artwork art ON o.artwork_id = art.id
LEFT JOIN file f on f.id = bsv.file_id OR f.id = art.file_id
...
所以我想 LEFT JOIN
至少被多个列之一引用的所有文件:
SELECT
...
FROM
O o
LEFT JOIN binary_stream_value bsv ON o.binary_stream_value_id = bsv.id
LEFT JOIN artwork art ON o.artwork_id = art.id
LEFT JOIN (SELECT f.id FROM file f WHERE f.id = bsv.file_id OR f.id = art.file_id) f ON TRUE
...
失败
ERROR: invalid reference to FROM-clause entry for table "bsv"
LINE 212: ... LEFT JOIN (SELECT f.id FROM file f WHERE f.id = bsv.file_i...
^
HINT: There is an entry for table "bsv", but it cannot be referenced from this part of the query.
诚然,我一半希望这会失败,一半希望我错了。
编写此类查询的正确方法是什么?
你需要一个横向连接来完成你想做的事情:
SELECT
...
FROM
O o
LEFT JOIN binary_stream_value bsv ON o.binary_stream_value_id = bsv.id
LEFT JOIN artwork art ON o.artwork_id = art.id
LEFT JOIN LATERAL (SELECT f.id FROM file f WHERE f.id = bsv.file_id OR f.id = art.file_id) f ON TRUE
...
但是子select并不是真正必要的开头:
SELECT
...
FROM
O o
LEFT JOIN binary_stream_value bsv ON o.binary_stream_value_id = bsv.id
LEFT JOIN artwork art ON o.artwork_id = art.id
LEFT JOIN file f on f.id = bsv.file_id OR f.id = art.file_id
...