如何在Oracle语法中使用双重条件进行LEFT JOIN?

时间:2018-09-12 21:06:35

标签: sql oracle oracle11g oracle10g left-join

我有2张桌子。

1)汽车表:

car table

2)参数表:

param table

我需要提取具有 owner 参数匹配且在 insurance 中没有区别的重复汽车(这必须是相同的,或者两者都不存在< / strong>)。

我已成功使用ANSI语法中的LEFT JOIN执行查询:

SELECT owner.name, owner.value, COALESCE (insur.name, 'insurance'), insur.value, count(*)
FROM car INNER JOIN param owner ON car.id = owner.car_id
LEFT JOIN param insur ON car.id = insur.car_id AND insur.name = 'insur'
WHERE owner.name = 'owner'
GROUP BY owner.name, owner.value, insur.name, insur.value
HAVING count(*) > 1

SQL Fiddle with properly working ANSI-syntax

但是当我用Oracle语法中的(+)符号代替LEFT JOIN重写此查询时,我得到了不同的结果:

SELECT owner.name, owner.value, COALESCE (insur.name, 'insurance'), insur.value, count(*)
FROM car,
     param owner,
     param insur
WHERE car.id = owner.car_id
  AND owner.name = 'owner'
  AND car.id (+) = insur.car_id -- key change
  AND insur.name = 'insur'
GROUP BY owner.name, owner.value, insur.name, insur.value
HAVING count(*) > 1

SQL Fiddle with unexpected result of (+) instead LEFT JOIN

此查询的结果为空。我不明白如何用Oracle语法重写它以得到相同的查询结果。

1 个答案:

答案 0 :(得分:0)

那是

SQL> select owner.name, owner.value,
  2    coalesce (insur.name, 'insurance') in_name,
  3    insur.value, count(*)
  4  from car, param owner, param insur
  5  where car.id = owner.car_id
  6    and car.id  = insur.car_id (+)
  7    and insur.name (+) = 'insur'
  8    and owner.name = 'owner'
  9  group by owner.name, owner.value, insur.name, insur.value
 10  having count(*) > 1;

NAME     VALUE    IN_NAME              VALUE      COUNT(*)
-------- -------- -------------------- -------- ----------
owner    John     insurance                              2

SQL>

但是,为什么为什么要使用 old Oracle外连接语法?与ANSI连接相比,它仅具有缺点,而没有优点(至少,我没有想到)。实际上,我知道一个-如果您在旧的Forms&Reports 6i中使用外部联接(甚至更旧?我认为现在没有人使用这些版本),则它们的内置 PL / SQL引擎可能不会 ANSI外部联接,所以您注定要使用旧的(+)外部联接运算符。除此之外...不,不知道。