是否有一种方法可以从一个表中全部选择,并在可能的情况下进行联接?

问题描述 投票:0回答:2

关于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;

但是我无法选择所有产品,即使没有带有缩略图的图像也是如此。

sql postgresql
2个回答
0
投票

您需要将缩略图的条件从WHERE移到JOIN条件:

select ..
FROM products p 
  LEFT  JOIN product_files pf ON p.id=pf.product_id AND pf.is_thumbnail=true;

0
投票

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子句中后续表的过滤条件。

© www.soinside.com 2019 - 2024. All rights reserved.