首页 > 解决方案 > 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'

该语句返回正确的结果。但我认为它没有优化。有没有办法让它更快?

标签: sqlsql-server

解决方案


INCASE想到:

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)

注意:我删除了数字周围的单引号。我假设这些实际上是数字而不是字符串。如果它们是字符串,则保留单引号。


推荐阅读