Left join inner join в чем разница
Перейти к содержимому

Left join inner join в чем разница

  • автор:

Понимание джойнов сломано. Это точно не пересечение кругов, честно

Так получилось, что я провожу довольно много собеседований на должность веб-программиста. Один из обязательных вопросов, который я задаю — это чем отличается INNER JOIN от LEFT JOIN.

Чаще всего ответ примерно такой: «inner join — это как бы пересечение множеств, т.е. остается только то, что есть в обеих таблицах, а left join — это когда левая таблица остается без изменений, а от правой добавляется пересечение множеств. Для всех остальных строк добавляется null». Еще, бывает, рисуют пересекающиеся круги.

Я так устал от этих ответов с пересечениями множеств и кругов, что даже перестал поправлять людей.

Дело в том, что этот ответ в общем случае неверен. Ну или, как минимум, не точен.

Давайте рассмотрим почему, и заодно затронем еще парочку тонкостей join-ов.

Во-первых, таблица — это вообще не множество. По математическому определению, во множестве все элементы уникальны, не повторяются, а в таблицах в общем случае это вообще-то не так. Вторая беда, что термин «пересечение» только путает.

(Update. В комментах идут жаркие споры о теории множеств и уникальности. Очень интересно, много нового узнал, спасибо)

INNER JOIN

Давайте сразу пример.

Итак, создадим две одинаковых таблицы с одной колонкой id, в каждой из этих таблиц пусть будет по две строки со значением 1 и еще что-нибудь.

Давайте, их, что ли, поджойним

Если бы это было «пересечение множеств», или хотя бы «пересечение таблиц», то мы бы увидели две строки с единицами.

На практике ответ будет такой:

Для начала рассмотрим, что такое CROSS JOIN. Вдруг кто-то не в курсе.

CROSS JOIN — это просто все возможные комбинации соединения строк двух таблиц. Например, есть две таблицы, в одной из них 3 строки, в другой — 2:

Тогда CROSS JOIN будет порождать 6 строк.

Так вот, вернемся к нашим баранам.
Конструкция

— это, можно сказать, всего лишь синтаксический сахар к

Т.е. по сути INNER JOIN — это все комбинации соединений строк с неким фильтром condition . В общем-то, можно это представлять по разному, кому как удобнее, но точно не как пересечение каких-то там кругов.

Небольшой disclaimer: хотя inner join логически эквивалентен cross join с фильтром, это не значит, что база будет делать именно так, в тупую: генерить все комбинации и фильтровать. На самом деле там более интересные алгоритмы.

LEFT JOIN

Если вы считаете, что левая таблица всегда остается неизменной, а к ней присоединяется или значение из правой таблицы или null, то это в общем случае не так, а именно в случае когда есть повторы данных.

Опять же, создадим две таблицы:

Теперь сделаем LEFT JOIN:

Результат будет содержать 5 строк, а не по количеству строк в левой таблице, как думают очень многие.

Так что, LEFT JOIN — это тоже самое что и INNER JOIN (т.е. все комбинации соединений строк, отфильтрованных по какому-то условию), и плюс еще записи из левой таблицы, для которых в правой по этому фильтру ничего не совпало.

LEFT JOIN можно переформулировать так:

Сложноватое объяснение, но что поделать, зато оно правдивее, чем круги с пересечениями и т.д.

Условие ON

Удивительно, но по моим ощущениям 99% разработчиков считают, что в условии ON должен быть id из одной таблицы и id из второй. На самом деле там любое булево выражение.

Например, есть таблица со статистикой юзеров users_stats, и таблица с ip адресами городов.
Тогда к статистике можно прибавить город

где && — оператор пересечения (см. расширение посгреса ip4r)

Если в условии ON поставить true, то это будет полный аналог CROSS JOIN

Производительность

Есть люди, которые боятся join-ов как огня. Потому что «они тормозят». Знаю таких, где есть полный запрет join-ов по проекту. Т.е. люди скачивают две-три таблицы себе в код и джойнят вручную в каком-нибудь php.

Это, прямо скажем, странно.

Если джойнов немного, и правильно сделаны индексы, то всё будет работать быстро. Проблемы будут возникать скорее всего лишь тогда, когда у вас таблиц будет с десяток в одном запросе. Дело в том, что планировщику нужно определить, в какой последовательности осуществлять джойны, как выгоднее это сделать.

Сложность этой задачи O(n!), где n — количество объединяемых таблиц. Поэтому для большого количества таблиц, потратив некоторое время на поиски оптимальной последовательности, планировщик прекращает эти поиски и делает такой план, какой успел придумать. В этом случае иногда бывает выгодно вынести часть запроса в подзапрос CTE; например, если вы точно знаете, что, поджойнив две таблицы, мы получим очень мало записей, и остальные джойны будут стоить копейки.

Кстати, Еще маленький совет по производительности. Если нужно просто найти элементы в таблице, которых нет в другой таблице, то лучше использовать не ‘LEFT JOIN… WHERE… IS NULL’, а конструкцию EXISTS. Это и читабельнее, и быстрее.

Выводы

Как мне кажется, не стоит использовать диаграммы Венна для объяснения джойнов. Также, похоже, нужно избегать термина «пересечение».

Как объяснить на картинке джойны корректно, я, честно говоря, не представляю. Если вы знаете — расскажите, плиз, и киньте в коменты.

Update В этом видео я наглядно объясняю, как правильно визуализировать джойны (English):

Update2 Продолжение статьи здесь: https://habr.com/ru/post/450528/

Больше полезного можно найти на telegram-канале о разработке «Cross Join», где мы обсуждаем базы данных, языки программирования и всё на свете!

SQL Joins – LEFT Join, RIGHT Join, and INNER Join Explained

Zubair Idris Aweda

Zubair Idris Aweda

SQL Joins – LEFT Join, RIGHT Join, and INNER Join Explained

SQL is a programming language we use to interact with relational databases. SQL databases contain tables, which contain rows of data. These tables usually contain similar or related data.

In an office management web application database, you would have tables for employees , their departments , their managers , the projects they work on, and so on depending on the structure of your application.

In the employees table, you would find data like the employee ID, name, salary, department ID (used to link the employee to the department), and other fields that match your needs. The other tables would also contain data for their specific entities.

What Are Joins?

If you ever need to bring multiple tables in your database together to access the data, you use a JOIN.

Joins let you fetch data that is scattered across tables. For example, using the database tables that we’ll create in a moment, we’ll be able to get all the details of an employee, along with their manager name, and department they’re working in by using a join.

A join lets you use a single query to achieve this. You use a join because you can only get this data by bringing data from the employees table, departments table, and projects table together. In simple terms, you would be JOIN-ing these tables together.

To perform a join, you use the JOIN keyword. And we’ll see how it works in this tutorial.

Prerequisites:

To continue with this tutorial, you should know the basics of insertion and retrieval operations with SQL.

Also, you can setup a demo database that we’ll use for this article. The database should have tables like this:

SQL to quickly setup the tables used in the article

How to Use an Inner Join in SQL

There are many types of joins in SQL, and each one has a different purpose.

The inner join is the most basic type of join. It is so basic that sometimes, you can omit the JOIN keyword and still perform an inner join.

For example, say you want to fetch the name of all employees in the organanization, along with the name of their departments. In a situation like this, you need data from both the employees table and the departments table. A simple join like this would do:

A very simple JOIN query

So how does this actually work? To start with, take a look at the FROM part of the query:

Here, data is being fetched from more than one table, and each table is aliased. The alias is very useful for scenarios where both tables have similarly named fields, like the id field both tables have in this case. You would be able to access the different fields easily using the short alias created.

Next, in the SELECT part of the query, we also specify the columns we want (and we use the alias to tell which table each value comes from):

And finally, to ensure only correct values are matched to each other, the WHERE part of the query specifies the conditions that have to be met for the data to be joined.

So for the first employee, the dept_id is 1 , so we fetch the department with id = 1 , and it’s name is returned. This happens for as many rows as there are in the employees table.

The result of the query looks like this:

Screenshot-2023-01-07-at-15.45.09

Result of JOIN query

Here, notice that the number of employees returned is smaller than the number of employees that actually exist. This is because when you use an INNER JOIN, you only get records that exist in both tables.

That is, the employee with id = 6 that was not returned has a dept_it = 8 . Now, this department isn’t in the departments table, so it wasn’t returned.

Another way to achieve this same result would be to actually spell out the JOIN like this:

Or use the INNER JOIN like this:

These queries return exactly the same result as the first one. But they are more readable as they’re explicit.

In these queries, you’re selecting from the employees table, then joining the departments table to the result. The ON in the query is used to specify the conditions on which to JOIN. It’s the same as the WHERE condition in the first query.

INNER JOIN Use Case

In real applications, you use an INNER JOIN when only records that exist in both tables matter.

For example, in an inventory management application, you could have a table for sales , and another for products . Now, the sales table will contain product_id (a reference to the sold product), along with other details like sold_at (when the product was sold) and maybe customer details.

The products table, on the other hand, will have the name , price , and maybe the quantity of every product.

Now say it’s end of the week and you need to do a sales report. You would need to fetch all sales records, along with the product name and price to display on a dashboard or export as a CSV of some sort.

To do this, you would use an INNER JOIN of the products table on the sales table, because you do not care about products that were not sold – you only want to see every sale that was made, and the name and price of the product that was sold. Every other product will be exempted from this report.

How to Use a Left Join in SQL

In another scenario, you might want to fetch all the employee names and their department names, but this time without leaving any employee or department name out. Here, you’d you use a LEFT JOIN.

In a LEFT JOIN, every record from the table on the left, the base table, will be returned. Then values from the right table, the table being joined, will be added where they exist.

The LEFT JOIN is also known as LEFT OUTER JOIN and you can use them interchangeably.

So to fetch all employee and department names, you can modify the previous query to use LEFT JOIN, like this:

The result of this query looks like this now:

Screenshot-2023-01-07-at-15.55.10

Result of LEFT JOIN

Now, employee with id = 6 and dept_id = 8 is returned, with the department name being set as NULL because there is no department with id = 8 .

LEFT JOIN Use Case

In real applications, you use a LEFT JOIN when there’s a primary, always existing entity that can be related to another entity that doesn’t always exist.

An easy use case would be in a multi-vendor ecommerce application where after a user signs up, they can set up a store and add products to the store.

A user, on signing up, doesn’t automatically have a store until they create it. So if you try to view all users, with their store details, you would use a LEFT JOIN of the stores table on the users table. This is because every record in the users table is important, store or no store.

When the user has a store set up, the store details are returned, and if otherwise, NULL is returned. But, you wouldn’t be losing any existing data.

How to Use a Right Join in SQL

The RIGHT JOIN works like the opposite of the LEFT JOIN. In a RIGHT JOIN, every record from the table on the right, the table being joined, will be returned. Then values from the left table, the base table, will be added where they exist.

The RIGHT JOIN is also known as the RIGHT OUTER JOIN and you can use them interchangeably.

An example would be to modify the previous query to use a RIGHT JOIN instead of a LEFT JOIN, like this:

Now, your result looks like this:

Screenshot-2023-01-07-at-16.02.08

Result of RIGHT JOIN

Now, every department in the departments table was returned. And employees in those departments were returned too. For the last row, there is no employee with dept_id = 4 , which is why the NULL value gets returned.

RIGHT JOIN Use Case

The RIGHT JOIN works exactly as the LEFT JOIN works in real applications. The difference between them comes from the level of importance of the tables to be joined.

The LEFT JOIN is more commonly used because you very likely will write your query from left to right, listing tables in that order of importance too. Otherwise, the RIGHT JOIN works exactly as the LEFT JOIN.

How to Combine JOINS in SQL

So far, we’ve only joined one table to another. But, you can actually join as many tables as you like by using any or all of these joins together as you like.

For example, say you want to fetch the names of all employees, with their department names, manager names, and projects names. You would have to join the employees table to the departments table, the managers table, and the projects table. You can achieve this using this query:

In this query, start from the employees table as a base table. Then you LEFT JOIN the departments table. You also LEFT JOIN the managers table, and finally, the projects table.

The result of this query will look like this:

Screenshot-2023-01-07-at-19.30.29

Result of general JOIN query

The reason for using a LEFT JOIN here is because you have to fetch ALL employees. You could use an INNER JOIN in place of the LEFT JOIN in the managers table because all employees have a manager_id that actually exists in the managers table. But to be safe, you can just use the LEFT JOIN.

How to Use a Cross Join in SQL

This is also known as a CARTESIAN JOIN. It returns every record from both tables in a multiplication-like manner. It returns every possible combination of rows from both tables. It doesn’t need a JOIN condition like the other JOINs.

For example, if you do a CROSS JOIN between tables employees and departments , your result will look like this:

Screenshot-2023-01-07-at-20.19.24

CROSS JOIN employees and departments table. CROSS JOIN of employees and departments tables.

Here you have 24 rows, which is a product of the number of rows in the employees table, 6, and the number of rows in the departments table, 4. The records were returned so that for every record in the employees table, it is mapped to a record in the departments table.

CROSS JOIN Use Case

A common use case of CROSS JOIN would be in an ecommerce application where it is possible to have size or color variations of all products. If you ever need to fetch a list of all products in different sizes, like this:

Screenshot-2023-01-10-at-13.13.55

Result of a basic CROSS JOIN

This result was gotten from CROSS JOINing a sizes table that contains an id for each size, a string size that can be either ‘Small’, ‘Medium’, or ‘Large’ and another field called ratio to affect how this size affects the product price. So, for every product, it is mapped to a size, and the price is calculated.

How to Use a Self Join in SQL

As the name implies, is when you try to join a table to itself. There is no self JOIN keyword.

Take this new categories table, for example. This table contains both main categories and sub-categories. If you ever have to fetch the categories and their sub-categories, you can use a SELF JOIN.

Create categories table. Self JOIN query

Here, see how the table was referenced twice. Be careful with the alias as it’s important in differentiating both instances. The result of this query looks like this:

Screenshot-2023-01-07-at-21.40.25Result of simple Self JOIN on categories table

SELF JOIN Use Case

In many applications, you find hierarchical data stored in a single table. Like the category and sub-category as shown in the previous example. Or as in employee and manager, because they’re both employees of the company.

In case of the latter, the table will have fields such as id , name , manager_id (this is basically the id of another employee). Let’s say you want to write a query where you have to fetch a list of managers and the number of their employees. Given that these managers are also employees, you only have one table to fetch from, the employees table. To do this fetch, do a SELF JOIN of the employees table on the employees table like this:

This would correctly return the managers and the number of employees working under them.

Summary

I hope you now understand SQL JOINs, the different types, and when to use them so you can write better queries.

All the JOINs here work with MySQL. There are other JOINs like FULL OUTER JOIN and NATURAL JOIN that we didn’t discuss, but you can look into them yourself if you like.

If you have any questions or relevant advice, please get in touch with me to share them.

To read more of my articles or follow my work, you can connect with me on LinkedIn, Twitter, and Github. It’s quick, it’s easy, and it’s free!

Left join inner join в чем разница

JOIN is a method of combining (joining) information from two tables. The result is a stitched set of columns from both tables, defined by the join type (INNER/OUTER/CROSS and LEFT/RIGHT/FULL, explained below) and join criteria (how rows from both tables relate).

A table may be joined to itself or to any other table. If information from more than two tables needs to be accessed, multiple joins can be specified in a FROM clause.

# Self Join

A table may be joined to itself, with different rows matching each other by some condition. In this use case, aliases must be used in order to distinguish the two occurrences of the table.

In the below example, for each Employee in the example database Employees table

(opens new window) , a record is returned containing the employee’s first name together with the corresponding first name of the employee’s manager. Since managers are also employees, the table is joined with itself:

This query will return the following data:

Employee Manager
John James
Michael James
Johnathon John

# So how does this work?

The original table contains these records:

Id FName LName PhoneNumber ManagerId DepartmentId Salary HireDate
1 James Smith 1234567890 NULL 1 1000 01-01-2002
2 John Johnson 2468101214 1 1 400 23-03-2005
3 Michael Williams 1357911131 1 2 600 12-05-2009
4 Johnathon Smith 1212121212 2 1 500 24-07-2016

The first action is to create a Cartesian product of all records in the tables used in the FROM clause. In this case it’s the Employees table twice, so the intermediate table will look like this (I’ve removed any fields not used in this example):

e.Id e.FName e.ManagerId m.Id m.FName m.ManagerId
1 James NULL 1 James NULL
1 James NULL 2 John 1
1 James NULL 3 Michael 1
1 James NULL 4 Johnathon 2
2 John 1 1 James NULL
2 John 1 2 John 1
2 John 1 3 Michael 1
2 John 1 4 Johnathon 2
3 Michael 1 1 James NULL
3 Michael 1 2 John 1
3 Michael 1 3 Michael 1
3 Michael 1 4 Johnathon 2
4 Johnathon 2 1 James NULL
4 Johnathon 2 2 John 1
4 Johnathon 2 3 Michael 1
4 Johnathon 2 4 Johnathon 2

The next action is to only keep the records that meet the JOIN criteria, so any records where the aliased e table ManagerId equals the aliased m table Id :

e.Id e.FName e.ManagerId m.Id m.FName m.ManagerId
2 John 1 1 James NULL
3 Michael 1 1 James NULL
4 Johnathon 2 2 John 1

Then, each expression used within the SELECT clause is evaluated to return this table:

e.FName m.FName
John James
Michael James
Johnathon John

Finally, column names e.FName and m.FName are replaced by their alias column names, assigned with the AS

Employee Manager
John James
Michael James
Johnathon John

# Differences between inner/outer joins

SQL has various join types to specify whether (non-)matching rows are included in the result: INNER JOIN , LEFT OUTER JOIN , RIGHT OUTER JOIN , and FULL OUTER JOIN (the INNER and OUTER keywords are optional). The figure below underlines the differences between these types of joins: the blue area represents the results returned by the join, and the white area represents the results that the join will not return.

Venn diagrams representing SQL inner/outer joins

Cross Join SQL Pictorial Presentation (reference

enter image description here

Below are examples from this

For instance there are two tables as below :

Note that (1,2) are unique to A, (3,4) are common, and (5,6) are unique to B.

# Inner Join

An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common:

# Left outer join

A left outer join will give all rows in A, plus any common rows in B:

# Right outer join

Similarly, a right outer join will give all rows in B, plus any common rows in A:

# Full outer join

A full outer join will give you the union of A and B, i.e., all the rows in A and all the rows in B. If something in A doesn’t have a corresponding datum in B, then the B portion is null, and vice versa.

# JOIN Terminology: Inner, Outer, Semi, Anti.

Let’s say we have two tables (A and B) and some of their rows match (relative to the given JOIN condition, whatever it may be in the particular case):

Join Terminology Overview

We can use various join types to include or exclude matching or non-matching rows from either side, and correctly name the join by picking the corresponding terms from the diagram above.

The examples below use the following test data:

# Inner Join

Combines left and right rows that match.

Inner Join

# Left Outer Join

Sometimes abbreviated to "left join". Combines left and right rows that match, and includes non-matching left rows.

Left Outer Join

# Right Outer Join

Sometimes abbreviated to "right join". Combines left and right rows that match, and includes non-matching right rows.

Right Outer Join

# Full Outer Join

Sometimes abbreviated to "full join". Union of left and right outer join.

Full Outer Join

# Left Semi Join

Includes left rows that match right rows.

Left Semi Join

# Right Semi Join

Includes right rows that match left rows.

Right Semi Join

As you can see, there is no dedicated IN syntax for left vs. right semi join — we achieve the effect simply by switching the table positions within SQL text.

# Left Anti Semi Join

Includes left rows that do not match right rows.

Left Anti Semi Join

WARNING: Be careful if you happen to be using NOT IN on a NULL-able column! More details here

# Right Anti Semi Join

Includes right rows that do not match left rows.

Right Anti Semi Join

As you can see, there is no dedicated NOT IN syntax for left vs. right anti semi join — we achieve the effect simply by switching the table positions within SQL text.

# Cross Join

A Cartesian product of all left with all right rows.

Cross join is equivalent to an inner join with join condition which always matches, so the following query would have returned the same result:

# Self-Join

This simply denotes a table joining with itself. A self-join can be any of the join types discussed above. For example, this is a an inner self-join:

# Left Outer Join

A Left Outer Join (also known as a Left Join or Outer Join) is a Join that ensures all rows from the left table are represented; if no matching row from the right table exists, its corresponding fields are NULL .

The following example will select all departments and the first name of employees that work in that department. Departments with no employees are still returned in the results, but will have NULL for the employee name:

This would return the following from the example database

Departments.Name Employees.FName
HR James
HR John
HR Johnathon
Sales Michael
Tech NULL

# So how does this work?

There are two tables in the FROM clause:

Id FName LName PhoneNumber ManagerId DepartmentId Salary HireDate
1 James Smith 1234567890 NULL 1 1000 01-01-2002
2 John Johnson 2468101214 1 1 400 23-03-2005
3 Michael Williams 1357911131 1 2 600 12-05-2009
4 Johnathon Smith 1212121212 2 1 500 24-07-2016
Id Name
1 HR
2 Sales
3 Tech

First a Cartesian product is created from the two tables giving an intermediate table.
The records that meet the join criteria (Departments.Id = Employees.DepartmentId) are highlighted in bold; these are passed to the next stage of the query.

As this is a LEFT OUTER JOIN all records are returned from the LEFT side of the join (Departments), while any records on the RIGHT side are given a NULL marker if they do not match the join criteria. In the table below this will return Tech with NULL

Id Name Id FName LName PhoneNumber ManagerId DepartmentId Salary HireDate
1 HR 1 James Smith 1234567890 NULL 1 1000 01-01-2002
1 HR 2 John Johnson 2468101214 1 1 400 23-03-2005
1 HR 3 Michael Williams 1357911131 1 2 600 12-05-2009
1 HR 4 Johnathon Smith 1212121212 2 1 500 24-07-2016
2 Sales 1 James Smith 1234567890 NULL 1 1000 01-01-2002
2 Sales 2 John Johnson 2468101214 1 1 400 23-03-2005
2 Sales 3 Michael Williams 1357911131 1 2 600 12-05-2009
2 Sales 4 Johnathon Smith 1212121212 2 1 500 24-07-2016
3 Tech 1 James Smith 1234567890 NULL 1 1000 01-01-2002
3 Tech 2 John Johnson 2468101214 1 1 400 23-03-2005
3 Tech 3 Michael Williams 1357911131 1 2 600 12-05-2009
3 Tech 4 Johnathon Smith 1212121212 2 1 500 24-07-2016

Finally each expression used within the SELECT clause is evaluated to return our final table:

Departments.Name Employees.FName
HR James
HR John
Sales Richard
Tech NULL

# Implicit Join

Joins can also be performed by having several tables in the from clause, separated with commas , and defining the relationship between them in the where clause. This technique is called an Implicit Join (since it doesn’t actually contain a join clause).

All RDBMSs support it, but the syntax is usually advised against. The reasons why it is a bad idea to use this syntax are:

  • It is possible to get accidental cross joins which then return incorrect results, especially if you have a lot of joins in the query.
  • If you intended a cross join, then it is not clear from the syntax (write out CROSS JOIN instead), and someone is likely to change it during maintenance.

The following example will select employee’s first names and the name of the departments they work for:

This would return the following from the example database

e.FName d.Name
James HR
John HR
Richard Sales

# Basic explicit inner join

A basic join (also called "inner join") queries data from two tables, with their relationship defined in a join clause.

The following example will select employees’ first names (FName) from the Employees table and the name of the department they work for (Name) from the Departments table:

This would return the following from the example database

Employees.FName Departments.Name
James HR
John HR
Richard Sales

# CROSS JOIN

Cross join does a Cartesian product of the two members, A Cartesian product means each row of one table is combined with each row of the second table in the join. For example, if TABLEA has 20 rows and TABLEB has 20 rows, the result would be 20*20 = 400 output rows.

d.Name e.FName
HR James
HR John
HR Michael
HR Johnathon
Sales James
Sales John
Sales Michael
Sales Johnathon
Tech James
Tech John
Tech Michael
Tech Johnathon

It is recommended to write an explicit CROSS JOIN if you want to do a cartesian join, to highlight that this is what you want.

# Joining on a Subquery

Joining a subquery is often used when you want to get aggregate data from a child/details table and display that along with records from the parent/header table. For example, you might want to get a count of child records, an average of some numeric column in child records, or the top or bottom row based on a date or numeric field. This example uses aliases, which arguable makes queries easier to read when you have multiple tables involved. Here’s what a fairly typical subquery join looks like. In this case we are retrieving all rows from the parent table Purchase Orders and retrieving only the first row for each parent record of the child table PurchaseOrderLineItems.

# CROSS APPLY & LATERAL JOIN

A very interesting type of JOIN is the LATERAL JOIN (new in PostgreSQL 9.3+),
which is also known as CROSS APPLY/OUTER APPLY in SQL-Server & Oracle.

The basic idea is that a table-valued function (or inline subquery) gets applied for every row you join.

This makes it possible to, for example, only join the first matching entry in another table.
The difference between a normal and a lateral join lies in the fact that you can use a column that you previously joined in the subquery that you "CROSS APPLY".

left | right | inner JOIN LATERAL

CROSS | OUTER APPLY

INNER JOIN LATERAL is the same as CROSS APPLY
and LEFT JOIN LATERAL is the same as OUTER APPLY

Example usage (PostgreSQL 9.3+):

And for SQL-Server

# FULL JOIN

One type of JOIN that is less known, is the FULL JOIN.
(Note: FULL JOIN is not supported by MySQL as per 2016)

A FULL OUTER JOIN returns all rows from the left table, and all rows from the right table.

If there are rows in the left table that do not have matches in the right table, or if there are rows in right table that do not have matches in the left table, then those rows will be listed, too.

Note that if you’re using soft-deletes, you’ll have to check the soft-delete status again in the WHERE-clause (because FULL JOIN behaves kind-of like a UNION);
It’s easy to overlook this little fact, since you put AP_SoftDeleteStatus = 1 in the join clause.

Also, if you are doing a FULL JOIN, you’ll usually have to allow NULL in the WHERE-clause; forgetting to allow NULL on a value will have the same effects as an INNER join, which is something you don’t want if you’re doing a FULL JOIN.

# Recursive JOINs

Recursive joins are often used to obtain parent-child data. In SQL, they are implemented with recursive common table expressions

# Syntax
  • [ < INNER | < < LEFT | RIGHT | FULL >[ OUTER ] > > ] JOIN
# Remarks

Joins, as their name suggests, are a way of querying data from several tables in a joint fashion, with the rows displaying columns taken from more than one table.

В чем разница между INNER, LEFT и RIGHT JOIN?

В данной статье я раскрою разницу между SQL-запросами INNER, LEFT и RIGHT JOIN. Здесь описываются базовые случаи, для каждой конкретной платформы (MySQL, MSSQL, Oracle и прочих) могут быть свои нюансы.

INNER JOIN

Возвращаются все записи из таблиц table_01 и table_02, связанные посредством primary/foreign ключей, и соответствующие условию WHERE для таблицы table_01. Если в какой-либо из таблиц отсутствует запись, соответствующая соседней, то в выдачу такая пара включена не будет. Иными словами, выдадутся только те записи, которые есть и в первой, и во второй таблице. То есть выборка идет фактически по связи (ключу), выдадутся только те записи, которые связаны между собой. «Одинокие» записи, для которых нет пары в связи, выданы не будут.

LEFT JOIN

Возвращаются все данные из «левой» таблицы, даже если не найдено соответствий в «правой» таблице («левая» таблица в SQL-запросе стоит левее знака равно, «правая» — правее, то есть обычная логика правой и левой руки). Иными словами, если мы присоединяем к «левой» таблице «правую», то выберутся все записи в соответствии с условиями WHERE для левой таблицы. Если в «правой» таблице не было соответствий по ключам, они будут возвращены как NULL. Таким образом, здесь главной выступает «левая» таблица, и относительно нее идет выдача. В условии ON «левая» таблица прописывается первой по порядку (table_01), а «правая» – второй (table_02):

RIGHT JOIN

Возвращаются все данные из «правой» таблицы, даже если не найдено соответствий в «левой» таблице. То есть примерно также, как и в LEFT JOIN, только NULL вернется для полей «левой» таблицы. Грубо говоря, эта выборка ставит во главу угла правую «таблицу», относительно нее идет выдача. Обратите внимание на WHERE в следующем примере, условие выборки затрагивает «правую» таблицу:

Таким образом, мы разложили по полочкам, в чем отличие INNER, LEFT и RIGHT JOIN. Разумеется, представленная выше информация не нова, но она может быть полезна начинающим программистам, которые часто путаются в типах запросов.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *