[英]Postgresql left join
I have two tables cars
and usage
.我有两张桌子cars
和usage
。 I create a record in usage once a month for some of cars.我每月为某些汽车创建一次使用记录。 Now I want to get distinct list of cars with their latest usage that I saved.现在我想获得我保存的最新使用情况的不同汽车列表。
first of all look at the tables please首先请看一下表格
cars:
| id | model | reseller_id |
|----|-------------|-------------|
| 1 | Samand Sall | 324228 |
| 2 | Saba 141 | 92933 |
usages:
| id | car_id | year | month | gas |
|----|--------|------|-------|-----|
| 1 | 2 | 2020 | 2 | 68 |
| 2 | 2 | 2020 | 3 | 94 |
| 3 | 2 | 2020 | 4 | 33 |
| 4 | 2 | 2020 | 5 | 12 |
I tried a lot of ways but none of them is good enough.我尝试了很多方法,但没有一个足够好。 because sometimes this query gets me one ofnot latest records of usages.因为有时这个查询让我得到一个非最新的使用记录。
SELECT * FROM cars AS c
LEFT JOIN
(select *
from usages
) u on (c.id = u.car_id)
order by u.gas desc
You can do this with a DISTINCT ON in the derived table:您可以在派生表中使用 DISTINCT ON 执行此操作:
SELECT *
FROM cars AS c
LEFT JOIN (
select distinct on (u.car_id) *
from usages u
order by u.car_id, u.year desc, u.month desc
) lu on c.id = lu.car_id
order by u.gas desc;
I think you need window function row_number
.我认为您需要 window function row_number
。 Here is the demo .这是演示。
select
id,
model,
reseller_id
from
(
select
c.id,
model,
reseller_id,
row_number() over (partition by u.car_id order by u.id desc) as rn
from cars c
left join usages u
on c.id = u.car_id
) subq
where rn = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.