postgresql - How can I select into a temporary variable mid sql statement
问题描述
I have following sql statement:
select * from funds_balance where account_id = 7 and sequence_number <= (
select sequence_number from funds_balance where account_id = 7 and update_settlement_pool_id = 7
union all
select sequence_number from funds_balance_history where account_id = 7 and update_settlement_pool_id = 7
limit 1
)
union all
select account_id, deliverable_id, cash, credit,pending,sequence_number, update_time,update_reason, update_funds_action_id, update_trade_serial, update_settlement_pool_id
from funds_balance_history where account_id = 7 and sequence_number <= (
select sequence_number from funds_balance where account_id = 7 and update_settlement_pool_id = 7
union all
select sequence_number from funds_balance_history where account_id = 7 and update_settlement_pool_id = 7
limit 1
)
order by sequence_number desc limit 2
In the above complex statement there are two identical sub-queries which I assume are executing twice.
Is there any way to only execute this sub-query once, maybe storing it some kind of temp variable to reference in the outer query?
Pseudo code below describing what I mean:
var seq_num = select sequence_number from funds_balance where account_id = 7 and update_settlement_pool_id = 7
union all
select sequence_number from funds_balance_history where account_id = 7 and update_settlement_pool_id = 7
limit 1
select * from funds_balance where account_id = 7 and sequence_number <= seq_num
union all
select account_id, deliverable_id, cash, credit,pending,sequence_number, update_time,update_reason, update_funds_action_id, update_trade_serial, update_settlement_pool_id
from funds_balance_history where account_id = 7 and sequence_number <= seq_num
order by sequence_number desc limit 2
解决方案
要将您的预期行为简单地转换为 SQL 查询,您可以为此使用CTE(WITH
子句):
WITH seq_num AS (
select sequence_number from funds_balance where account_id = 7 and update_settlement_pool_id = 7
union all
select sequence_number from funds_balance_history where account_id = 7 and update_settlement_pool_id = 7
limit 1
)
select * from funds_balance where account_id = 7
and sequence_number <= (SELECT sequence_number FROM seq_num)
union all
select account_id, deliverable_id, cash, credit,pending,sequence_number, update_time,update_reason, update_funds_action_id, update_trade_serial, update_settlement_pool_id
from funds_balance_history where account_id = 7
and sequence_number <= (SELECT sequence_number FROM seq_num)
推荐阅读
- mysql - MySQL 显示 SQL 错误:1048 作为警告而不是错误
- git - 在 Azure Devops (VSTS) 中删除 git fork 关系
- node.js - 在 Mocha 中使脚本返回失败
- ngxs - 我们可以通过 ofActionErrored() 处理 ngxs @Action 错误而不使用默认的“ErrorHandler”吗?
- java - 使用 KeyBindings 调用方法
- java - 是否有任何用于 Java 的替代 SDK 来访问 AWS DynamoDB?
- android - 如何用 FragmentPagerAdapter 在每个 Fragment 中实现不同的数据?
- python - 如何在 Python 中获取函数的路径?
- rust - 如何使用表示带有 StructOpt 的子命令的枚举?
- javascript - JavaScript 刽子手游戏 - 为正确猜测的每个单词播放特定歌曲