简体   繁体   中英

POSTGRES SQL Left Join return only the largest UID on the right table?

I'm trying to left outer join two tables, my left table contains 1 row, my right table contains 3 rows for the associated left row. I want to only return 1 row using the largest ID numerical value from the right table.

Should i not be using a left join?

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)

Where table plan / p contains an ID that is the FK to inventory, but also contains column UID which is a auto-increment column indicating the revision.

Looking up the correct value from the plan table:

select * from plan order by plan.uid limit 1

This clearly wont work inside the query as it only returns the same row for the join.

Assuming you mean "the latest UID for each ID", you can join to a derived table that picks the largest 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM