How to do LEFT JOIN with double condition in Oracle syntax?

前提是你 提交于 2020-07-20 03:57:45

问题


I have 2 tables.

1) car table:

2) param table:

I need to fetch duplicate cars have owner params match and do NOT differ in insurance (that's it must be either the same or is absent for both).

I'm successfully executing my query with LEFT JOIN in ANSI-syntax:

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

But when I rewrote this query with (+) sign from Oracle syntax instead LEFT JOIN I have different result:

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

Result of this query is empty. I don't understand how to rewrite it in Oracle syntax to have the same result of queries.


回答1:


That would be

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>

Though, why would you want to use the old Oracle outer-join syntax? When compared to ANSI joins, it has only drawbacks and no advantages (at least, I can't think of any). Actually, I know one - if you use outer join in old Forms & Reports 6i (or even older? I don't think that anyone uses those versions nowadays), their built-in PL/SQL engine might not speak ANSI outer joins so you're doomed to use the old (+) outer join operator. Other than that ... nope, no idea.



来源:https://stackoverflow.com/questions/52303492/how-to-do-left-join-with-double-condition-in-oracle-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!