gpt4 book ai didi

database - 如何使用 PostgresQL 进行多选

转载 作者:行者123 更新时间:2023-11-29 13:39:02 32 4
gpt4 key购买 nike

我有两个表:destinationweather_forecast 我正在获取最新的 weather_forecast(按 reference_time 排序),如下所示:

SELECT destination_id, reference_time FROM weather_forecast 
WHERE destination_id = (SELECT id FROM destination WHERE slug = 'prague')
AND reference_time < now()
ORDER BY reference_time DESC
LIMIT 1;

For slug prague(布拉格市)。

我需要为一千个城市做这个查询...

显然,使用循环来调用它不是最优的:

const SLUG_LIST = ['prague', 'new-york', .... next 1000 items]
const weather = db.select...

有没有更好的方法如何使用某种最佳方式来做到这一点?有些选择基于数组中的项目列表?

谢谢!

最佳答案

您可以使用 ROW_NUMBER() 对每个目的地的 reference_time 降序排列天气预报,然后筛选最近的预报:

SELECT *
FROM (
SELECT
d.slug,
w.destination_id,
w.reference_time,
ROW_NUMBER() OVER(PARTITION BY w.destination_id ORDER BY w.reference_time DESC) rn
FROM weather_forecast w
INNER JOIN destination d ON d.id = w.destination_id
WHERE w.reference_time < now()
) x
WHERE rn = 1

关于database - 如何使用 PostgresQL 进行多选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58158755/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com