database - 如何使用 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...
有没有更好的方法如何使用某种最佳方式来做到这一点?有些选择基于数组中的项目列表?
谢谢!
解决方案
您可以使用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
推荐阅读
- php - Symfony SwiftMailer:如果控制器没有返回 $this->render() 响应,则不发送
- nestjs - 如何将 fastify 速率限制器应用于 Nest JS 中的单个路由?
- soap - 无法理解相关 XSD 文件的 SOAP 路径解析
- orm - 有没有办法在运行时动态地将属性添加到 Sails.js 中的初始化模型?
- json - Laravel - 如何从 JSON 中提取值到文本框中
- windows - "heroku config | grep REDIS" 如何在 windows cmd 上制定
- windows - Aero Snap 后将 WinForms 窗口恢复到正确位置
- java - Java 中 AM/PM 的时差
- c++ - QT 多线程和更新 GUI
- java - 部署到快照本地未在快照中找到