sql - Sql server join 代替 union
问题描述
我有代理可以有很多政策的关系。某些代理处于“主要”代理角色,其中一些处于“子代理”角色。
我正在尝试查找分配给与主代理 x 或子代理 y 相同策略的所有代理。
在这种情况下有没有办法避免联合?
我已经提取了 with 语句中的共同部分。现在很少有策略应该被标记为 MAIN 并且很少被标记为 SUB。
with active_agents_on_policy as
(
select po.code, ag.number
from policy as po
inner join agent as ag on po.id = ag.policy_id
where ag.status = 'active'
and po.status = 'active'
)
select *, 'MAIN' from active_agents_on_policy tmp1 inner join active_agents_on_policy tmp2 on tmp1.code = tmp2.code
where tmp1.agent_id = '112'
UNION
select *, 'SUB' from active_agents_on_policy tmp1 inner join active_agents_on_policy tmp2 on tmp1.code = tmp2.code
where tmp1.agent_id = '634'
该语句返回正确的结果。但我认为它没有优化。有没有办法让它更快?
解决方案
IN
并CASE
想到:
select *,
(case when tmp1.agent_id in (112) then 'MAIN' else 'SUB' END)
from active_agents_on_policy tmp1 inner join
active_agents_on_policy tmp2
on tmp1.code = tmp2.code
where tmp1.agent_id in (112, 634)
注意:我删除了数字周围的单引号。我假设这些实际上是数字而不是字符串。如果它们是字符串,则保留单引号。
推荐阅读
- graphql - 有没有办法强制从服务器端断开苦艾图订阅?
- excel - 尝试将列中的选定单词数更改为不同的单词 Excel VBA
- syntax - YAML 使用 neovim 和 treesitter 缩进?
- sql - Oracle SQL 创建汇总总计
- firebase - 在 Xamarin Forms 上收到推送通知时,如何在后台服务中运行代码
- android - Android Studio 可重用的 xml 值
- raspberry-pi - 无法为本地网络打开端口 443
- regex - 正则表达式获取两个字符之间的第 N 个单词
- r - 手动为轴标题着色(ggplot2)
- raster - 超出栅格数组的范围