Postgresql 左连接
Postgresql left join
我有两个表 cars
和 usage
。我每月为一些汽车创建一次使用记录。
现在我想获得不同的汽车列表以及我保存的最新使用情况。
请先看一下表格
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 |
问题就在这里
- 我只需要年月的最新用法
我尝试了很多方法,但其中 none 已经足够了。因为有时这个查询会让我得到一份不是最新的使用记录。
SELECT * FROM cars AS c
LEFT JOIN
(select *
from usages
) u on (c.id = u.car_id)
order by u.gas desc
我认为你需要 window 函数 row_number
。这是 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
您可以在派生的 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;
我有两个表 cars
和 usage
。我每月为一些汽车创建一次使用记录。
现在我想获得不同的汽车列表以及我保存的最新使用情况。
请先看一下表格
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 |
问题就在这里
- 我只需要年月的最新用法
我尝试了很多方法,但其中 none 已经足够了。因为有时这个查询会让我得到一份不是最新的使用记录。
SELECT * FROM cars AS c
LEFT JOIN
(select *
from usages
) u on (c.id = u.car_id)
order by u.gas desc
我认为你需要 window 函数 row_number
。这是 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
您可以在派生的 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;