Oracle SQL连接或条件

Oracle SQL连接或条件,sql,oracle,Sql,Oracle,我想确认是否有可能加入和或条件(对我来说,它不起作用): 我尝试了一个等价的查询,但它没有运行。如何使其工作?是的,这是可能的——在ON子句中允许使用任何布尔表达式,甚至是子查询 或通常是性能杀手 类似这样的查询: 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.*,

我想确认是否有可能加入和或条件(对我来说,它不起作用):

我尝试了一个等价的查询,但它没有运行。如何使其工作?

是的,这是可能的——在
ON
子句中允许使用任何布尔表达式,甚至是子查询

通常是性能杀手

类似这样的查询:

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

两个这样的连接通常效率更高。

您想过使用UNION而不是OR吗?
从逻辑上讲,并集是OR的等价形式。 例如:

SELECT * FROM table_a
LEFT JOIN table_b ON table_a.field_1 = table_b.field_1 
UNION
SELECT * FROM table_a
LEFT JOIN table_b ON table_a.field_2 = table_b.field_2
;

这两个表中较大的一个应该有两个索引(一个在字段_1上,另一个在字段_2上)。将对较小的表进行完整扫描,然后对联接进行索引范围扫描。

能否提供一些示例数据和预期结果?谢谢!我得到了它。你的问题比你说的好得多。只是想了解更多,我最初的查询不起作用。可以吗?它运行了一段时间,结果显示与ON子句中的字段相关的错误。
SELECT * FROM table_a
LEFT JOIN table_b ON table_a.field_1 = table_b.field_1 
UNION
SELECT * FROM table_a
LEFT JOIN table_b ON table_a.field_2 = table_b.field_2
;