如何在PostgreSQL中隐藏具有相同引用ID的不同行集

时间:2015-08-05 09:47:03

标签: sql postgresql

我有2个相关的SQL表:

购买

id (PK),  
code,  
status (complete, void)

接收

id (PK),  
code,  
purchase_id (FK),  
status (complete, void)

Purchase有许多Receiving(一对多)

如果LEFT JOIN的结果是

----------------------------------------------------------------------------------------
|Purchase.id|Purchase.code|Purchase.status|Receiving.id|Receiving.code|Receiving.status|
----------------------------------------------------------------------------------------
| 1         | PO001       | complete      | 1          | RG001        | complete       | X HIDE
| 2         | PO002       | complete      | 2          | RG002        | void           | X HIDE
| 2         | PO002       | complete      | 3          | RG003        | complete       | X HIDE
| 2         | PO003       | complete      | NULL       | NULL         | NULL           | V SHOW
| 3         | PO004       | complete      | 4          | RG004        | void           | V SHOW

关键是我想显示“购买”,只有当“接收”状态未完成并且为空时 所以结果应该只显示PO003和PO004。

PO002不应该显示,因为它已经完成了“接收” 而PO001也不会显示,因为它已经有1个完整的“接收”。

我希望你们得到我的意思。我如何在SQL上查询它?

2 个答案:

答案 0 :(得分:0)

在查询中添加WHERE条件。

SELECT p.id, p.code, p.status, r.id, r.code, r.status
FROM Purchase p
INNER JOIN Receiving r ON p.id = r.purchase_id
WHERE r.id IS NULL
AND r.status != 'complete'

答案 1 :(得分:0)

试试这个;

select *
from  Purchase p 
join Receiving R 
on p.id = r.purchase_id 
where
r.id not in (
  select id
  from Receiving
  where 
  status = 'complete' or
  status is not null
)