Поддержка  •  Дневник  •  Без рекламы  •  О сайте  •  Реклама  •  Поставить баннер  •  Fleshlight  •  Прислать  •  Хроника  •  Translate Гости: 11    Участники: 0 Авторизация Авторизация   Регистрация 
Метод Научного Тыка
RULVEN
Поиск  
Blackball iMag | интернет-журнал
Каталог


Начало » Разработка ПО » Visual representation of SQL joins
Мне повезёт!

Visual representation of SQL joins


Добавлено: Ср 03.04.2024 • Sergeant
Источник: источник
Просмотров: 16
Комментарии: 0


Introduction

This is just a simple article visually explaining SQL JOINs.

Background

I'm a pretty visual person. Things seem to make more sense as a picture. I looked all over the Internet for a good graphical representation of SQL JOINs, but I couldn't find any to my liking. Some had good diagrams but lacked completeness (they didn't have all the possible JOINs), and some were just plain terrible. So, I decided to create my own and write an article about it.

Using the code

I am going to discuss seven different ways you can return data from two relational tables. I will be excluding cross Joins and self referencing Joins. The seven Joins I will discuss are shown below:

  1. INNER JOIN
  2. LEFT JOIN
  3. RIGHT JOIN
  4. OUTER JOIN
  5. LEFT JOIN EXCLUDING INNER JOIN
  6. RIGHT JOIN EXCLUDING INNER JOIN
  7. OUTER JOIN EXCLUDING INNER JOIN

For the sake of this article, I'll refer to 5, 6, and 7 as LEFT EXCLUDING JOIN, RIGHT EXCLUDING JOIN, and OUTER EXCLUDING JOIN, respectively. Some may argue that 5, 6, and 7 are not really joining the two tables, but for simplicity, I will still refer to these as Joins because you use a SQL Join in each of these queries (but exclude some records with a WHERE clause).

Inner JOIN

This is the simplest, most understood Join and is the most common. This query will return all of the records in the left table (table A) that have a matching record in the right table (table B). This Join is written as follows:

SELECT <select_list>
FROM Table_A A
INNER JOIN Table_B B
ON A.Key = B.Key

Left JOIN 

 

This query will return all of the records in the left table (table A) regardless if any of those records have a match in the right table (table B). It will also return any matching records from the right table. This Join is written as follows:

SELECT <select_list>
FROM Table_A A
LEFT JOIN Table_B B
ON A.Key = B.Key

Right JOIN

 

This query will return all of the records in the right table (table B) regardless if any of those records have a match in the left table (table A). It will also return any matching records from the left table. This Join is written as follows:

SELECT <select_list>
FROM Table_A A
RIGHT JOIN Table_B B
ON A.Key = B.Key

Outer JOIN 

 

This Join can also be referred to as a FULL OUTER JOIN or a FULL JOIN. This query will return all of the records from both tables, joining records from the left table (table A) that match records from the right table (table B). This Join is written as follows:

SELECT <select_list>
FROM Table_A A
FULL OUTER JOIN Table_B B
ON A.Key = B.Key

Left Excluding JOIN 

 

This query will return all of the records in the left table (table A) that do not match any records in the right table (table B). This Join is written as follows:

SELECT <select_list>
FROM Table_A A
LEFT JOIN Table_B B
ON A.Key = B.Key
WHERE B.Key IS NULL

Right Excluding JOIN 

 

This query will return all of the records in the right table (table B) that do not match any records in the left table (table A). This Join is written as follows:

SELECT <select_list>
FROM Table_A A
RIGHT JOIN Table_B B
ON A.Key = B.Key
WHERE A.Key IS NULL

Outer Excluding JOIN 

 

This query will return all of the records in the left table (table A) and all of the records in the right table (table B) that do not match. I have yet to have a need for using this type of Join, but all of the others, I use quite frequently. This Join is written as follows:

SELECT <select_list>
FROM Table_A A
FULL OUTER JOIN Table_B B
ON A.Key = B.Key
WHERE A.Key IS NULL OR B.Key IS NULL

Examples

Suppose we have two tables, Table_A and Table_B. The data in these tables are shown below:

TABLE_A
  PK Value
---- ----------
   1 FOX
   2 COP
   3 TAXI
   6 WASHINGTON
   7 DELL
   5 ARIZONA
   4 LINCOLN
  10 LUCENT
TABLE_B
  PK Value
---- ----------
   1 TROT
   2 CAR
   3 CAB
   6 MONUMENT
   7 PC
   8 MICROSOFT
   9 APPLE
  11 SCOTCH

The results of the seven Joins are shown below:

-- INNER JOIN
SELECT A.PK AS A_PK, A.Value AS A_Value,
       B.Value AS B_Value, B.PK AS B_PK
FROM Table_A A
INNER JOIN Table_B B
ON A.PK = B.PK
A_PK A_Value    B_Value    B_PK
---- ---------- ---------- ----
   1 FOX        TROT          1
   2 COP        CAR           2
   3 TAXI       CAB           3
   6 WASHINGTON MONUMENT      6
   7 DELL       PC            7
(5 row(s) affected)

 

-- LEFT JOIN
SELECT A.PK AS A_PK, A.Value AS A_Value,
B.Value AS B_Value, B.PK AS B_PK
FROM Table_A A
LEFT JOIN Table_B B
ON A.PK = B.PK
A_PK A_Value    B_Value    B_PK
---- ---------- ---------- ----
   1 FOX        TROT          1
   2 COP        CAR           2
   3 TAXI       CAB           3
   4 LINCOLN    NULL       NULL
   5 ARIZONA    NULL       NULL
   6 WASHINGTON MONUMENT      6
   7 DELL       PC            7
  10 LUCENT     NULL       NULL
(8 row(s) affected)

 

-- RIGHT JOIN
SELECT A.PK AS A_PK, A.Value AS A_Value,
B.Value AS B_Value, B.PK AS B_PK
FROM Table_A A
RIGHT JOIN Table_B B
ON A.PK = B.PK
A_PK A_Value    B_Value    B_PK
---- ---------- ---------- ----
   1 FOX        TROT          1
   2 COP        CAR           2
   3 TAXI       CAB           3
   6 WASHINGTON MONUMENT      6
   7 DELL       PC            7
NULL NULL       MICROSOFT     8
NULL NULL       APPLE         9
NULL NULL       SCOTCH       11
(8 row(s) affected)

 

-- OUTER JOIN
SELECT A.PK AS A_PK, A.Value AS A_Value,
B.Value AS B_Value, B.PK AS B_PK
FROM Table_A A
FULL OUTER JOIN Table_B B
ON A.PK = B.PK
A_PK A_Value    B_Value    B_PK
---- ---------- ---------- ----
   1 FOX        TROT          1
   2 COP        CAR           2
   3 TAXI       CAB           3
   6 WASHINGTON MONUMENT      6
   7 DELL       PC            7
NULL NULL       MICROSOFT     8
NULL NULL       APPLE         9
NULL NULL       SCOTCH       11
   5 ARIZONA    NULL       NULL
   4 LINCOLN    NULL       NULL
  10 LUCENT     NULL       NULL
(11 row(s) affected) 

 

-- LEFT EXCLUDING JOIN
SELECT A.PK AS A_PK, A.Value AS A_Value,
B.Value AS B_Value, B.PK AS B_PK
FROM Table_A A
LEFT JOIN Table_B B
ON A.PK = B.PK
WHERE B.PK IS NULL
A_PK A_Value    B_Value    B_PK
---- ---------- ---------- ----
   4 LINCOLN    NULL       NULL
   5 ARIZONA    NULL       NULL
  10 LUCENT     NULL       NULL
(3 row(s) affected)

 

-- RIGHT EXCLUDING JOIN
SELECT A.PK AS A_PK, A.Value AS A_Value,
B.Value AS B_Value, B.PK AS B_PK
FROM Table_A A
RIGHT JOIN Table_B B
ON A.PK = B.PK
WHERE A.PK IS NULL
A_PK A_Value    B_Value    B_PK
---- ---------- ---------- ----
NULL NULL       MICROSOFT     8
NULL NULL       APPLE         9
NULL NULL       SCOTCH       11
(3 row(s) affected)

 

-- OUTER EXCLUDING JOIN
SELECT A.PK AS A_PK, A.Value AS A_Value,
B.Value AS B_Value, B.PK AS B_PK
FROM Table_A A
FULL OUTER JOIN Table_B B
ON A.PK = B.PK
WHERE A.PK IS NULL
OR B.PK IS NULL
A_PK A_Value    B_Value    B_PK
---- ---------- ---------- ----
NULL NULL       MICROSOFT     8
NULL NULL       APPLE         9
NULL NULL       SCOTCH       11
   5 ARIZONA    NULL       NULL
   4 LINCOLN    NULL       NULL
  10 LUCENT     NULL       NULL
(6 row(s) affected)

 

Note on the OUTER JOIN that the inner joined records are returned first, followed by the right joined records, and then finally the left joined records (at least, that's how my Microsoft SQL Server did it; this, of course, is without using any ORDER BY statement).

You can visit the Wikipedia article for more info here (however, the entry is not graphical).

I've also created a cheat sheet that you can print out if needed. If you right click on the image below and select "Save Target As...", you will download the full size image.



Мне нравится 0   Мне не нравится 0



Комментарии

Чтобы добавить видео с YouTube, нужно написать [@youtube=xxxxx] , где xxxxx – ID видео.


Комментарии: 0
Нет ни одного комментария.
RSS-лента
Поделиться ссылкой:
Алкогольные игры для компании — как спасти вечеринку, если стало скучно Алкогольные игры для компании — как спасти вечеринку, если стало скучно
Обзор Sony Xperia XA2 Ultra: планшетофон с двумя селфи-камерами и хорошей автономностью Обзор Sony Xperia XA2 Ultra: планшетофон с двумя селфи-камерами и хорошей автономностью
Ужасные свидания
12 самых вкусных рецептов поджарки из свинины 12 самых вкусных рецептов поджарки из свинины
Желе из мяты — десерт для гурманов Желе из мяты — десерт для гурманов
3 опасные ошибки, которые допускают многие водители при доливке антифриза 3 опасные ошибки, которые допускают многие водители при доливке антифриза
Пары выбирают свинг Пары выбирают свинг
Истязания половых органов
Медовик с творожным кремом Медовик с творожным кремом
Грог: рецепт в домашних условиях, правила приготовления Грог: рецепт в домашних условиях, правила приготовления

database
Ср 03.04.2024
Visual representation of SQL joins
Ср 17.01.2024
Top 9 Entity Framework Core features in 2023 you can’t miss
Practical Azure SQL Database for Modern Developers Вт 09.01.2024
Practical Azure SQL Database for Modern Developers
Год: 2021
The Definitive Guide to SQLite, Second Edition Чт 24.03.2022
The Definitive Guide to SQLite, Second Edition
Год: 2010
PostgreSQL Server Programming, Second Edition Вт 15.03.2022
PostgreSQL Server Programming, Second Edition
Год: 2015
Troubleshooting PostgreSQL Чт 03.03.2022
Troubleshooting PostgreSQL
Год: 2015
PostgreSQL Developer's Guide Вт 01.03.2022
PostgreSQL Developer's Guide
Год: 2015
Работа с PostgreSQL, настройка и масштабирование Чт 24.02.2022
Работа с PostgreSQL, настройка и масштабирование
Год: 2014
PostgreSQL Cookbook Вт 22.02.2022
PostgreSQL Cookbook
Год: 2015
PostgreSQL Administration Cookbook, 9.5/9.6 Edition Чт 17.02.2022
PostgreSQL Administration Cookbook, 9.5/9.6 Edition
Год: 2017
Practical MongoDB: Architecting, Developing, and Administering MongoDB Вт 15.02.2022
Practical MongoDB: Architecting, Developing, and Administering MongoDB
Год: 2015
MongoDB in Action Чт 10.02.2022
MongoDB in Action
Год: 2011
PostgreSQL High Availability Cookbook, Second Edition Чт 30.12.2021
PostgreSQL High Availability Cookbook, Second Edition
Год: 2017
NHibernate 4.0 Cookbook Вт 26.10.2021
NHibernate 4.0 Cookbook
Год: 2017
Pro SQL Server 2008 Policy-Based Management Чт 04.03.2021
Pro SQL Server 2008 Policy-Based Management
Год: 2010
The Definitive Guide to SQLite, 2nd Edition Вт 02.03.2021
The Definitive Guide to SQLite, 2nd Edition
Год: 2006
Пн 09.03.2020
14 вопросов об индексах в SQL Server, которые вы стеснялись задать
PostgreSQL 9.0 High Performance Вт 24.12.2019
PostgreSQL 9.0 High Performance
Год: 2010
MongoDB Cookbook, 2nd Edition Вт 03.12.2019
MongoDB Cookbook, 2nd Edition
Год: 2016
Пн 29.07.2019
Dapper - King of Micro ORM (C#.NET)
Семь баз данных за семь недель. Введение в современные базы данных и идеологию NoSQL Вт 06.11.2018
Семь баз данных за семь недель. Введение в современные базы данных и идеологию NoSQL
Год: 2013
Next Generation Databases: NoSQL, NewSQL, and Big Data Вт 30.10.2018
Next Generation Databases: NoSQL, NewSQL, and Big Data
Год: 2015
Книги
Refactoring with C# Вт 23.04.2024
Refactoring with C#
Год: 2023
Building IoT Visualizations using Grafana Вт 09.04.2024
Building IoT Visualizations using Grafana
Год: 2022
Getting Started with Grafana Вт 02.04.2024
Getting Started with Grafana
Год: 2022

Разработано на основе BlackNight CMS
Release v.2024-04-19
© 2000–2024 Blackball
Дизайн & программирование:
О сайтеРеклама
Visitors
Web-site performed by Sergey Drozdov
BlackballРекламаСтатистикаПоддержка | МузыкаПлейлистыКиноВидеоИгрыАудиоПрограммыСтатьиКартинкиЮморФорумДневник сайтаПрислать контент