postgresql左连接

5us2dqdw  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(335)

我有两张table cars 以及 usage . 我每月为一些汽车创建一次使用记录。现在我想得到我保存的最新使用情况的汽车的不同列表。
首先请看table

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  |

问题就在这里

我只需要年和月的最新用法
我试过很多方法,但都不够好。因为有时候这个查询会让我得到一个最新的用法记录。

SELECT * FROM cars AS c
LEFT JOIN
     (select *
      from usages
     ) u on (c.id = u.car_id)
order by u.gas desc
7gs2gvoe

7gs2gvoe1#

可以使用派生表中的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;
6bc51xsx

6bc51xsx2#

我想你需要窗口功能 row_number . 这是演示。

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

相关问题