【发布时间】:2020-12-17 04:43:48
【问题描述】:
我们有一张这样的桌子
------------------------------------------
| user_id | timestamp | key | value |
------------------------------------------
99 | 1598603308 | Spo2 | 99
99 | 1598603318 | Spo2 | 98
99 | 1598603328 | Spo2 | 96
99 | 1598603338 | Spo2 | 97
...
...
99 | 1598603307 | Breath | 99
99 | 1598603311 | Breath | 98
99 | 1598603315 | Breath | 96
99 | 1598603319 | Breath | 97
我们的想法是为 id 为 99 的用户获取最新的 Breath 和最新的 Spo2。
select user_id, timestamp, key, value from session_records
where
user_id = 99 and key = 'Spo2' and value > 0 order by timestamp desc limit 1
**UNION**
select user_id, timestamp, key, value from session_records
where
user_id = 99 and key = 'Breath' and value >= 0 order by timestamp desc limit 1
现在key 可以变化。它可以是HeartRate 或Sdnn 或动态传入的东西。
有没有其他方法可以在没有联合的情况下编写此查询?
【问题讨论】:
-
UNION ALL至少会让它更快一点,但无论如何 GMB 的建议更好 -
查看我对your other question 的回复。该功能也应该适用于此。
标签: sql postgresql query-optimization greatest-n-per-group