implicit inner joins - are they equal?

橙三吉。 提交于 2021-01-29 18:00:20

问题


In my opinion these two SELECTs are exactly equal (but I want to rewrite the first for the second to help the optimizer in my case) - whatever data sits in tables a,b,c,d both SELECTs will produce exactly the same results. Do you agree? Thanks!

create table a (id number);
create table b (id number);
create table c (id number);
create table d (id number);

--Q1
select * from a,b,c,d
where a.id = b.id
and   a.id = c.id 
and   a.id = d.id;

--Q2
select * from a,b,c,d
where a.id = b.id
and   a.id = c.id 
and   a.id = d.id
      -- Q2 differs from Q1 only in the next 3 lines
and   b.id = c.id
and   b.id = d.id
and   c.id = d.id;

回答1:


I am going to address the question of whether those inequalities are always true. The answer is "no", not in SQL. Under most circumstances, they are equivalent. The problem arises with implicit type conversion.

In particular, if a.id is a number and other columns are strings, then you have the situation where:

1 = '1'        -- true
1 = '1.00'     -- true
'1' = '1.00'   -- false

You can see this on this db<>fiddle. It would be trivial to set this up using JOINs, but since I am not going to write code that has commas in the FROM clause, I'll leave that exercise to you.

In practice, id's used for joins should be of the same type. You cannot even declare a foreign key relationship if they are not. That best practice aside, the two queries are not automatically equivalent.

Note: This would be just as true if you used proper, explicit, standard JOIN syntax, which I strongly, strongly encourage you to learn and use exclusively.




回答2:


Yes, results will be exactly the same. To think of it algebraically, if a = b and b = c, then a = c. This means that the final three conditions in the second query are redundant.

I would say it is better to stick with the original query though. At best, the query optimizer will need to perform more comparisons.



来源:https://stackoverflow.com/questions/58117714/implicit-inner-joins-are-they-equal

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