sql - Oracle 连接到多个列中的任何一个
问题描述
我有一个关系表
NUM1 | NUM2 | NUM3
-- --- -----
1 2 3
2 4 5
3 4 null
3 4 null
以及 NUM 是主键的实际 INFO 表。
NUM | A_LOT_OF_OTHER_INFO
--- --------------------
1 asdff
2 werwr
3 erert
4 ghfgh
5 cvbcb
我想创建一个视图来查看出现在 RELATION 表的 NUM1、NUM2、NUM3 中的任何一个中的 NUM 的计数。
我的观点
NUM | A_LOT_OF_OTHER_INFO | TOTAL_COUNT
--- -------------------- ------------
1 asdff 1
2 werwr 2
3 erert 3
4 ghfgh 3
5 cvbcb 1
我可以通过从 RELATION 表中选择三个并将它们 UNION 来做到这一点,但我不想使用 UNION 因为表有很多记录,MY_VIEW 已经足够大,我正在寻找一种更好的方法来加入 RELATION视图中的表。你能建议一个方法吗?
解决方案
我会建议一个相关的子查询:
select i.*,
(select ((case when r.num1 = i.num then 1 else 0 end) +
(case when r.num2 = i.num then 1 else 0 end) +
(case when r.num3 = i.num then 1 else 0 end)
)
from relation r
where i.num in (r.num1, r.num2, r.num3)
) as total_count
from info i;
如果考虑性能,使用left join
s 可能会更快:
select i.*,
((case when r1.num1 is not null then 1 else 0 end) +
(case when r2.num1 is not null then 1 else 0 end) +
(case when r3.num1 is not null then 1 else 0 end)
) as total_count
from info i left join
relation r1
on i.num = r1.num1 left join
relation r2
on i.num = r2.num2 left join
relation r3
on i.num = r3.num3;
特别是,这将优化使用relation
: relation(num1)
、relation(num2)
和上的三个独立索引relation(num3)
。
推荐阅读
- python - 使用从列表中收集的项目搜索网站,然后返回 URL
- excel - 分配标头名称数组时范围循环提前退出?
- ios - 将对 IBOutlet 和 IBAction 的引用放在 viewDidLoad 内还是之前?
- javascript - 如何自动调整/调整 html5 textarea 元素的大小以适应初始内容?
- charts - 如何在栏中显示值 - GoogleChart/SQL
- node.js - 错误:Route.get() 需要回调函数,但尽管 module.exports = router; 但得到了 [object Undefined] 在那里?
- python - 尝试使用 os 使用 Python 打开视频,但控制台显示找不到目录
- jenkins - 从 BlueOcean 创建管道时如何从 Jenkinsfile 中选择作业名称
- android - Kotlin 插件更新后 Gradle 项目同步失败
- json - 使用递归时无法用字符串索引字符串