优化多个联合的查询
Optimize query for multiple unions
我们有一个table喜欢
------------------------------------------
| 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
或动态传入的内容。
有没有其他方法可以在不使用联合的情况下编写此查询?
只需使用distinct on
:
select distinct on (user_id, key) s.*
from session_record s
where user_id = 99 and key in ('Breath', 'Spo2')
order by user_id, key, timestamp desc
您可以根据需要调整 where
子句谓词 - 查询的其余部分保持不变。
我们有一个table喜欢
------------------------------------------
| 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
或动态传入的内容。
有没有其他方法可以在不使用联合的情况下编写此查询?
只需使用distinct on
:
select distinct on (user_id, key) s.*
from session_record s
where user_id = 99 and key in ('Breath', 'Spo2')
order by user_id, key, timestamp desc
您可以根据需要调整 where
子句谓词 - 查询的其余部分保持不变。