Postgresql 左外部联接在postgres上不起作用

Postgresql 左外部联接在postgres上不起作用,postgresql,join,Postgresql,Join,我有一个销售表、产品表和类别表,我正试图加入其中。我想要products表中与categories表中的行匹配的所有行。然后,我想加入sales表,但我只希望sales表中与products表匹配的行。这就是我的sql的样子: create table productsandcat as select p.p_id, p.p_name, p.p_price, c.c_name, s.s_price, s.quantity from products p join categories c o

我有一个销售表、产品表和类别表,我正试图加入其中。我想要products表中与categories表中的行匹配的所有行。然后,我想加入sales表,但我只希望sales表中与products表匹配的行。这就是我的sql的样子:

create table productsandcat as 
select p.p_id, p.p_name, p.p_price, c.c_name, s.s_price, s.quantity 
from products p
join categories c on p.cid = c.c_id
left outer join sales s on s.pid = p.p_id
但它并没有按预期工作。这将返回sales表中的所有行,但我只需要与products and categories表匹配的行

select p.p_id, p.p_name, p.p_price, c.c_name, s.s_price, s.quantity 
from products p
join categories c on p.cid = c.c_id
left outer join sales s on s.pid = p.p_id and s.cid = c.c_id
例如:

Products table:

p_id    p_name   p_price   cid
1        a          1       0
2        b          1        1
3        c           1       2

Categories table:
c_id   c_name
0         a1
1          a2
2          a3

sales table:
pid   quantity
1       1
4        1
5         2

productsandcat table:
p_id   p_name   p_price   c_name   s_price   quantity
1        a        1         a1        1      1
2        b        1         a2       0       0
3        c         1        a3       0       0  

您需要在左侧的外部联接上有一个AND,该联接具有类别表的条件

select p.p_id, p.p_name, p.p_price, c.c_name, s.s_price, s.quantity 
from products p
join categories c on p.cid = c.c_id
left outer join sales s on s.pid = p.p_id and s.cid = c.c_id
或者,如果您在销售中没有该类别,则不要使用左外部联接

select p.p_id, p.p_name, p.p_price, c.c_name, s.s_price, s.quantity 
from products p
join categories c on p.cid = c.c_id
join sales s on s.pid = p.p_id

如果我不使用左外连接,它就不能满足我的需要。我基本上是想把categories表和products表连接起来。然后拿我刚刚连接的那个表,和sales表做一个左外连接。可能吗?请在问题中添加表的结构,并添加一些样本行和样本输出,以说明您的目标,因为目前还不清楚。只是在问题中添加了一个样本。您使用创建表而不仅仅是选择表的具体原因是什么?是,这个表将有更多的计算在它上面执行,所以我需要使它成为一个表和一个视图将不做?跨表复制数据通常不是一个好主意。为了运行时,我将坚持使用表。我知道这不是个好主意,但是如果其他表发生变化,我会更新这个新表