postgresql左连接

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

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

  1. cars:
  2. | id | model | reseller_id |
  3. |----|-------------|-------------|
  4. | 1 | Samand Sall | 324228 |
  5. | 2 | Saba 141 | 92933 |
  1. usages:
  2. | id | car_id | year | month | gas |
  3. |----|--------|------|-------|-----|
  4. | 1 | 2 | 2020 | 2 | 68 |
  5. | 2 | 2 | 2020 | 3 | 94 |
  6. | 3 | 2 | 2020 | 4 | 33 |
  7. | 4 | 2 | 2020 | 5 | 12 |

问题就在这里

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

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

7gs2gvoe1#

可以使用派生表中的distinct on来执行此操作:

  1. SELECT *
  2. FROM cars AS c
  3. LEFT JOIN (
  4. select distinct on (u.car_id) *
  5. from usages u
  6. order by u.car_id, u.year desc, u.month desc
  7. ) lu on c.id = lu.car_id
  8. order by u.gas desc;
6bc51xsx

6bc51xsx2#

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

  1. select
  2. id,
  3. model,
  4. reseller_id
  5. from
  6. (
  7. select
  8. c.id,
  9. model,
  10. reseller_id,
  11. row_number() over (partition by u.car_id order by u.id desc) as rn
  12. from cars c
  13. left join usages u
  14. on c.id = u.car_id
  15. ) subq
  16. where rn = 1
展开查看全部

相关问题