POSTGRES SQL左联接仅返回右表上最大的UID吗?

时间:2019-03-11 19:09:31

标签: sql postgresql

我正在尝试使左外连接两个表,我的左表包含1行,我的右表包含3行,用于关联的左行。我只想使用右表中最大的ID数值返回1行。

我不应该使用左联接吗?

SELECT  
 (CASE WHEN p.invoice_number is null THEN 'Pending'
      WHEN p.sold_date is not null THEN 'Sold'
      ELSE 'Completed' 
  END),
  p.invoice_number,
  p.released_date
FROM 
  sales as s
  left join inventory as i on (s.id = i.id)
  left join plan as p on (i.id = p.id)

表计划/ p包含要库存的FK的ID,但还包含UID列,UID是指示修订的自动增量列。

从计划表中查找正确的值:

select * from plan order by plan.uid limit 1

这显然不会在查询中起作用,因为它只为连接返回同一行。

1 个答案:

答案 0 :(得分:1)

假设您的意思是“每个ID的最新UID”,则可以加入派生表,该表选择最大的UID

SELECT CASE 
         WHEN p.invoice_number is null THEN 'Pending'
         WHEN p.sold_date is not null THEN 'Sold'
         ELSE 'Completed' 
       END,
       p.invoice_number,
       p.released_date, 
       p.uid as latest_uid
FROM 
  sales as s
  left join inventory as i on s.id = i.id
  left join (
    select distinct on (id) id, uid
    from plan 
    order by id, uid desc 
  ) as p on i.id = p.id