简体   繁体   English

在 JPQL 中,在左连接的情况下,当我们在 ON 子句或 where 子句中给出特定条件时有什么区别吗?

[英]In JPQL, in case of left joins, is there any difference when we give a particular condition in ON clause or in where clause?

Is there any difference in these two queries in terms of processing and data obtained:这两个查询在处理和获取的数据方面有什么区别吗:

SELECT * from Table A Inner JOIN Table B ON A.id = B.id 
LEFT JOIN Table B ON A.id = C.id AND (C.status IS NULL OR C.status <>3) 
WHERE A.status = 1 and B.status = 1

OR或者

SELECT * from Table A Inner JOIN Table B ON A.id = B.id 
LEFT JOIN Table B ON A.id = C.id 
WHERE A.status = 1 and B.status = 1 AND (C.status IS NULL OR C.status <>3)

After a deep dive into left joins and different clauses, Here is what I have came up:在深入研究了左连接和不同的子句之后,我得出以下结论:

1) When to use where and on clauses in case of joins: 1) 在连接的情况下何时使用 where 和 on 子句:

In case of inner joins, it really does not matter where you give your conditions in where clause or on clause.在内部联接的情况下,在 where 子句或 on 子句中的何处给出条件并不重要。 Giving conditions in where clause will be used to filtering the data and giving the conditions in on clause will be to used to join the table.在where子句中给出条件将用于过滤数据,在on子句中给出条件将用于连接表。 For readability purpose it is good to provide the filtering conditions in where clause only just to make sure you convince your intent through your query.出于可读性目的,最好仅在 where 子句中提供过滤条件,以确保您通过查询说服您的意图。 But here is the catch, the query plan will change depending on where you pass your conditions and can heavily affect you.但这里有一个问题,查询计划会根据您传递条件的位置而改变,并且会严重影响您。 In case of outer joins(left, right, full) passing conditions blindly in where and on clause can give you incorrect data.在外连接(左、右、全)的情况下,在 where 和 on 子句中盲目地传递条件会给你不正确的数据。

2) When Left Join(or any outer join) can start behaving like inner joins Be careful when you specify filtering conditions for null values in where clause. 2) 当 Left Join(或任何外连接)开始表现得像内连接时 在 where 子句中为 null 值指定过滤条件时要小心。 Suppose you have two tables: Users and orders and you want irrespective of whether they have placed order or not, so we chose left join.假设你有两张表:Users和Orders,你想要不管他们有没有下单,所以我们选择了left join。 Further we have condition to filter condition like noOfOrders > 3, but since it was a left join values where null in products table.此外,我们有条件过滤条件,如 noOfOrders > 3,但由于它是左连接值,其中产品表中的 null。 All null values will be filtered out, since null<0, hence left join will behave like an inner join.所有 null 值都将被过滤掉,因为 null<0,因此左连接的行为类似于内部连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM