数据库左连接和右连接是可以相互转换的吧,不太确定理解对不对
这两种写法是等价的吗
select a.*, b.* from A a left join B b where a.bid = b.id select a.*, b.* from B b right join A a where a.bid = b.id
这两种写法是等价的吗
select a.*, b.* from A a left join B b where a.bid = b.id select a.*, b.* from B b right join A a where a.bid = b.id
我记得 MS SQL server books online 说得很清楚,关于这个概念。
就是如果 左表数据少,就用 left join, 右表数据少,就用 right join
@hemingyang
WHERE 和 ON 在 JOIN 情况下没有什么区别。SQL Server 不太了解,在 MySQL 里面,ON 部分的条件也可以写 WHERE 里面,但是习惯是 ON 写 JOIN 条件,WHERE 写结果条件。文档如下:
The search_condition used with ON is any conditional expression of the form that can be used in a WHERE clause. Generally, the ON clause serves for conditions that specify how to join tables, and the WHERE clause restricts which rows to include in the result set.
你说“WHERE 和 ON 在 JOIN 情况下没有什么区别”,你是说 inner join 吗?如果是的话,你说得没错,但是我想更加明确地说出,where 和 on 在 outer join 的表现是有区别的。
在“Database System Concepts 6th edition – Chapter 4 Intermediate SQL – 4.1 Join Expressions – 4.1.1 Join Conditions”中,说了“However, there are two good reasons for introducing the on condition. First, we shall see shortly that for a kind of join called an outer join, on conditions do behave in a manner different from where conditions. Second, an SQL query is often more readable by humans if the join condition is specified in the on clause and the rest of the conditions appear in the where clause.”。之后在“4.1.2 Outer Joins”中,它说“As we noted earlier, on and where behave differently for outer join. The reason for this is that outer join adds null-padded tuples only for those tuples that do not contribute to the result of the corresponding inner join. The on condition is part of the outer join specification, but a where clause is not.”。
我这里用例子演示一下 on 和 where 的区别吧。
create table t1(c1 int);
create table t2(c2 int);
insert into t1 values(1),(2),(3);
insert into t2 values(1);
select t1.*, t2.* from t1 left join t2 on t1.c1 = t2.c2; 的结果为
+——+——+
| c1 | c2 |
+——+——+
| 1 | 1 |
| 2 | NULL |
| 3 | NULL |
+——+——+
select t1.*, t2.* from t1 left join t2 on true where t1.c1 = t2.c2; 的结果为
+——+——+
| c1 | c2 |
+——+——+
| 1 | 1 |
+——+——+
虽然说 a left join b on a.bid = b.id 和 b right join a on a.bid = b.id 得到的结果是一样的,但是因为它们的 a 和 b 的顺序还是会造成处理的性能差异的,具体可以看看“Database System Concepts 6th edition – Chapter 12 Query Processing – 12.5 Join Operation”,因为内容是在太多了,在评论里讲不清楚。
这两条是等价的。
select t1.*, t2.* from t1 left join t2 on t1.c1 = t2.c2;
select t1.*, t2.* from t1 left join t2 where t1.c1 = t2.c2;