首页 > 解决方案 > 如何使用 PostgresSQL 进行多项选择

问题描述

我有两张桌子: destination而且weather_forecast我得到了最新的 weather_forecast(order by 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;

对于蛞蝓prague(布拉格市)。

我需要对一千个城市进行此查询...

绝对使用循环调用它不是最佳选择:

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

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

谢谢!

标签: databasepostgresql

解决方案


您可以使用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

推荐阅读