sql - Oracle SQL JOIN with OR condition
问题描述
I would like to confirm if it is possible to make a JOIn with and OR condition like (for me it is not working):
SELECT * FROM table_a
LEFT JOIN table_b
ON table_a.field_1 = table_b.field_1 OR table_a.field_2 = table_b.field_2
I tried it an equivalent query, but it was not running. How can I make it work?
解决方案
是的,这是可能的——ON
子句中允许使用任何布尔表达式,甚至是子查询。
OR
通常是性能杀手。
像这样的查询:
SELECT *
FROM table_a a LEFT JOIN
table_b b
ON a.field_1 = b.field_1 OR
a.field_2 = b.field_2;
经常可以改写为:
SELECT a.*,
COALESCE(b1.col, b2.col) as col -- choose the column value from one of the `b` tables
FROM table_a a LEFT JOIN
table_b b1
ON a.field_1 = b1.field_1 LEFT JOIN
table_b b2
ON b2.field_2 = b2.field_2 AND
b1.field_1 IS NULL -- no match on other column
两个这样的连接通常效率更高。
推荐阅读
- java - 尽管在测试中返回了一行,但 SQL ResultSet 为空
- android - Android Studio 如何使用 Fragment 在 Kotlin 中打开日期选择器
- tcl - 如何编写将创建模型和子电路名称列表的 Tcl 脚本
- haskell - 带有数据过滤器的列表中的最大值
- applescript - 如何在不导入任何图片的情况下将文件夹中的所有照片添加到 Apple Photos 相册?
- c++ - 对于下面发布的问题,我应该使用什么循环?
- javascript - Symfony5 - 由javascript XMLHttpRequest发送的formData对象未在控制器中提交
- vba - 如何使用 VBA 在 word 中打开受密码保护的 PDF 文件?
- r - 酒吧作为ggplot中的一堆正方形
- prolog - 坚持理解 Golog 解释器 - 我怎样才能避免硬编码?