关于SQL和PostgreSQL,我是一个初学者,所以我不知道这是否是一个显而易见的问题。我有两个表:产品和图像。我需要以某种方式选择所有产品,如果存在,则从图像表中选择其缩略图。
这是我到目前为止所拥有的:
CREATE TABLE products (
ID SERIAL PRIMARY KEY,
....
);
CREATE TABLE product_files (
ID SERIAL PRIMARY KEY,
product_id INTEGER NOT NULL REFERENCES products(ID),
is_thumbnail BOOLEAN NOT NULL DEFAULT FALSE,
...
);
SELECT p.id as product_id, p.status, p.title, p.description, pf.id, pf.file_name, pf.is_thumbnail
FROM products p LEFT JOIN product_files pf
ON p.id=pf.product_id
WHERE pf.is_thumbnail=true;
但是我无法选择所有产品,即使没有带有缩略图的图像也是如此。
您需要将缩略图的条件从WHERE移到JOIN条件:
select ..
FROM products p
LEFT JOIN product_files pf ON p.id=pf.product_id AND pf.is_thumbnail=true;
WHERE
子句将外部联接变为内部联接,因为不匹配项被滤除。
只需将条件移至ON
子句:
SELECT p.id as product_id, p.status, p.title, p.description, pf.id, pf.file_name, pf.is_thumbnail
FROM products p LEFT JOIN
product_files pf
ON p.id =pf.product_id AND pf.is_thumbnail;
= true
没什么错。但是,is_thumbnail
是布尔值,因此也没有理由进行显式比较。
过滤LEFT JOIN
的一般规则是将条件放在WHERE
子句的first表中。以及ON
子句中后续表的过滤条件。