Как объединить три таблицы в sql
Перейти к содержимому

Как объединить три таблицы в sql

  • автор:

SQL JOIN страница 4

Реляционные базы данных должны подчиняться требованиям целостности и неизбыточности данных, в связи с чем данные об одном бизнес-процессе могут содержаться не только в одной, двух, но и в трёх и более таблицах. В этих случаях для анализа данных используются цепочки соединённых таблиц: например, в одной (первой) таблице содержится некоторый количественный показатель, вторую таблицу с первой и третьей связывают внешние ключи — данные пересекаются, но только третья таблица содержит условие, в зависимости от которого может быть выведен количественный показатель из первой таблицы. И таблиц может быть ещё больше. При помощи оператора SQL JOIN в одном запросе можно соединить большое число таблиц. В таких запросах за одной секцией соединения следует другая, причём каждый следующий JOIN соединяет со следующей таблицей таблицу, которая была второй в предыдущем звене цепочки. Таким образом, синтаксис SQL запроса для соединения более двух таблиц следующий:

Пример 8. База данных — та же, что и в предыдущих примерах. К таблицам Categories и Parts в этом примере добавится таблица Ads, содержащая данные об опубликованных на портале объявлениях. Приведём фрагмент таблицы Ads, в котором среди записей есть записи о тех объявлениях, срок публикации которых истекает 2018-04-02.

A_Id Part_ID Date_start Date_end Text
21 1 ‘2018-02-11’ ‘2018-04-20’ «Продаю. «
22 1 ‘2018-02-11’ ‘2018-05-12’ «Продаю. «
. . . . .
27 1 ‘2018-02-11’ ‘2018-04-02’ «Продаю. «
28 2 ‘2018-02-11’ ‘2018-04-21’ «Продаю. «
29 2 ‘2018-02-11’ ‘2018-04-02’ «Продаю. «
30 3 ‘2018-02-11’ ‘2018-04-22’ «Продаю. «
31 4 ‘2018-02-11’ ‘2018-05-02’ «Продаю. «
32 4 ‘2018-02-11’ ‘2018-04-13’ «Продаю. «
33 3 ‘2018-02-11’ ‘2018-04-12’ «Продаю. «
34 4 ‘2018-02-11’ ‘2018-04-23’ «Продаю. «

Представим, что сегодня ‘2018-04-02’, то есть это значение принимает функция CURDATE() — текущая дата. Требуется узнать, к каким категориям принадлежат объявления, срок публикации которых истекает сегодня. Названия категорий есть только в таблице CATEGORIES, а даты истечения срока публикации объявлений — только в таблице ADS. В таблице PARTS — части категорий (или проще, подкатегории) опубликованных объявлений. Но внешним ключом Cat_ID таблица PARTS связана с таблицей CATEGORIES, а таблица ADS связана внешним ключом Part_ID с таблицей PARTS. Поэтому соединяем в одном запросе три таблицы и этот запрос можно с максимальной корректностью назвать цепочкой.

Запрос будет следующим:

Результат запроса — таблица, содержащая названия двух категорий — «Недвижимость» и «Транспорт»:

Cat_name
Недвижимость
Транспорт

Особенности соединения трех и более таблиц

Мы уже соединяли две и три таблицы и уяснили, что эта операция требуется тогда, когда требуется вывести значения столбцов не из одной, а из нескольких таблиц. Но значения столбцов из некоторых соединяемых таблиц вовсе не требуются в результате. Такие таблицы требуется включать в цепочки соединений, потому что только через их первичные и внешние ключи можно «достучаться» до других таблиц, в которых как раз и содержатся необходимые для результата данные.

Итак, нас ждут увлекательные соединения в цепочки уже не только трёх, а четырёх и пяти таблиц.

Работать будем с базой данных Mediastar. Схема базы данных — на рисунке ниже. Для увеличения рисунка щёлкните по нему левой кнопкой мыши.

Скачать архив со скриптом на SQL для установки этой базы со всеми данными можно по этой ссылке.

Рассмотрим каждую таблицу базы данных и установим, какие данные содержатся в каждом столбце каждой таблицы.

Таблица Reader (Читатель). Содержит данные о читателях медиа (сайтов), которые дали своё согласие на отслеживание их активности в сети. Данные анонимны. В нашей базе представлены 100 читателей, что представляет некоторую уменьшенную модель данных, используемых в реальных исследованиях. Данные были уменьшены во избежание громоздкости выводимых результатов. В таблице содержатся столбцы:

  • Reader_ID — идентификационный номер читателя, первичный ключ таблицы;
  • Age — возраст в годах;
  • Sex — пол (M — мужской, F — женский);
  • City_ID — идентификационный номер города проживания, внешний ключ, связывающий эту таблицу с таблицей City.

Таблица City (Город) В таблице содержатся столбцы:.

  • City_ID — идентификационный номер города, первичный ключ таблицы;
  • Name — название;
  • District — область;
  • Populsize — численность населения в тысячах человек.

Таблица Visit (Визит) Содержит данные о визитах в интернет в течение 4 недель в пределах одного месяца. В таблице содержатся столбцы:.

  • Visit_ID — идентификационный номер визита, первичный ключ таблицы;
  • Datetimestart — дата и время начала визита в формате ‘ДД-ММ-ГГГГ чч:мм:сс’;
  • Duration — продолжительность в секундах;
  • Reader_ID — идентификационный номер читателя, внешний ключ, связывающий эту таблицу с таблицей Reader;
  • Media_ID — идентификационный номер медиа (сайта), внешний ключ, связывающий эту таблицу с таблицей Media;
  • Adv_ID — идентификационный номер единицы рекламы, внешний ключ, связывающий эту таблицу с таблицей Advertisment.

Таблица Media (Медиа) Содержит данные о сайтах, на которые заходили читатели в течение 4 недель в пределах одного месяца. В таблице содержатся столбцы:.

  • Media_ID — идентификационный номер медиа, первичный ключ таблицы;
  • Name — название, например, «Всегда на колёсах»;
  • Mlevel — уровень, допустимые значения: «National» (национальный) «Regional» (региональный);
  • Mcont_ID — идентификационный типа содержания (контента) медиа, внешний ключ, связывающий эту таблицу с таблицей Mconttype;
  • Mtheme_ID — идентификационный темы медиа (сайта), внешний ключ, связывающий эту таблицу с таблицей Mediatheme.

Таблица Mconttype (Тип контента медиа) Содержит данные о типах контента сайтов. В таблице содержатся столбцы:.

  • Mcont_ID — идентификационный номер типа контента медиа, первичный ключ таблицы;
  • Ctype — тип контента медиа, состоит из латинских букв T (текст), A (аудио), V (видео), буквы располагаются в обозначении типа в порядке убывания удельного веса того или иного подтипа содержания.

Таблица Mediatheme (Тема медиа) Содержит данные о темах сайтов. В таблице содержатся столбцы:.

  • Mtheme_ID — идентификационный номер темы медиа, первичный ключ таблицы;
  • Name — название темы, например, «Авто», «Строительство», «Новости».

Таблица Advertisment (Реклама) Содержит данные о единицах рекламы, которая показывалась читателям во время визита. В таблице содержатся столбцы:.

  • Adv_ID — идентификационный номер единицы рекламы, первичный ключ таблицы;
  • Acont_ID — идентификационный типа содержания (контента) рекламы, внешний ключ, связывающий эту таблицу с таблицей Advconttype;
  • Advtheme_ID — идентификационный темы рекламы, внешний ключ, связывающий эту таблицу с таблицей Advtheme.

Таблица Advconttype (Тип контента рекламы) Содержит данные о типах контента сайтов. В таблице содержатся столбцы:.

  • Acont_ID — идентификационный номер типа контента рекламы, первичный ключ таблицы;
  • Advtype — тип контента рекламы, состоит из латинских букв T (текст), A (аудио), V (видео), буквы располагаются в обозначении типа в порядке убывания удельного веса того или иного подтипа содержания.

Таблица Advtheme (Тема рекламы) Содержит данные о темах рекламы. В таблице содержатся столбцы:.

  • Advtheme_ID — идентификационный номер темы рекламы, первичный ключ таблицы;
  • Name — название темы, например, «Авто», «Строительство», «Новости».

Пример 1. Вывести темы медиа (сайтов) и соответствующую каждой среднюю длительность просмотра. Отсортировать по возрастанию длительности просмотра.

Итак, в результирующей таблице будут столбцы из двух таблиц — Mediatheme и Visit. А таблица Media в цепочке из трёх соединяемых таблиц будет выполнять роль промежуточного звена, так как только через её первичный ключ Media_ID из таблицы Mediatheme можно достучаться до значений продолжительности просмотров в таблице Visit. Группировать достаточно по одному столбцу — Name из таблицы Mediatheme, так как применение агрегатной функции AVG к столбцу Duration из таблицы Visit обеспечивает автоматическую группировку по этому столбцу. Остаётся применить для сортировки оператор ORDER BY к столбцу Avgdur результирующей таблицы. Применение прямой сортировки (без дополнительного слова DESC) к столбцу с числовым типом данных даёт в результате выстраивание значений по возрастанию.

Запрос для выполнения этого задания должен быть таким:

В результате выполнения этого запроса будет выведена следующая таблица:

Если вы хотите выполнить запросы к базе данных из этого урока на MS SQL Server, но эта СУБД не установлена на вашем компьютере, то ее можно установить, пользуясь инструкцией по этой ссылке .

Должны ли соединяемые таблицы быть «соседями» по запросу?

Работаем с таблицами, показанными на рисунке ниже, кроме таблицы City. Для увеличения рисунка щёлкните по нему левой кнопкой мыши.

Пример 2. Вывести темы медиа (сайты), имеющие число просмотров, большее или равно числу просмотров всех медиа (сайтов), имеющих тип контента «VAT».

До сих пор мы рассматривали запросы, в которых условие в ключевом слове ON действовало для двух таблиц, между которыми располагался JOIN. А что делать, если требуется с какой-либо таблицей соединить не одну, а, например, две таблицы? Самое удобное решение — расположить эту ещё одну таблицу последней в запросе и далее задать условие ON. В этом примере в начале цепочки соединяются таблицы Mediatheme, Media и Mconttype. Но к таблице Media нужно «прицепить» ещё и таблицу Visit. Спокойно располагаем эту таблицу в конце запроса: JOIN Visit v, а в условии ON задаём совпадение значений Media_ID из этой таблицы и таблицы Media. Таким образом, соединяемые таблицы могут и не быть «соседями» по расположению в запросе.

А как решается эта задача в целом? Применяем кванторную функцию ALL. И основной запрос, и подзапрос в качестве критерия сравнения содержат число просмотров, определяемое агрегатной функцией COUNT. Следовательно, в основном запросе условие выборки должно быть задано не в секции WHERE, а оператором HAVING. В подзапросе же условие задаётся в секции WHERE. Для сравнения числа просмотров применяем оператор «больше или равно» (>=). Так как основной запрос содержит агрегатную фукнцию, не забываем произвести группировку по столбцу Name таблицы Mediatheme. Оператор группировки GROUP BY размещаем перед условием, заданным оператором HAVING.

Joining three tables using MySQL

And what would be for normalized form, if I want to find who is manager over other:

And wants to get this result:

Peter Mortensen's user avatar

11 Answers 11

Use ANSI syntax and it will be a lot more clear how you are joining the tables:

Machavity's user avatar

Peter Mortensen's user avatar

For normalize form

Don’t join like that. It’s a really really bad practice. It will slow down the performance in fetching with massive data. For example, if there were 100 rows in each tables, database server have to fetch 100x100x100 = 1000000 times. It had to fetch for 1 million times. To overcome that problem, join the first two table that can fetch result in minimum possible matching(It’s up to your database schema). Use that result in Subquery and then join it with the third table and fetch it. For the very first join —> 100×100= 10000 times and suppose we get 5 matching result. And then we join the third table with the result —> 5×100 = 500. Total fetch = 10000+500 = 10500 times only. And thus, the performance went up.

SQL Join 3 Tables – Join Query for Three Tables

In this tutorial, We will discuss SQL JOIN 3 tables with the best example. with this example, you will definitely become an expert in joining three or more tables. Even you will get the standard SQL join query for 3 tables that will be very useful to join the largest & complex tables.

As you know that we have always to write multiple select statements to select data from multiple tables. But It is not good for a large number of records & tables. It may increase the execution time or kill the queries. So, we need to write a single SELECT statement with SQL JOIN.

How to JOIN 3 tables in SQL? This is the most popular question that is frequently asked in the interview. So. It is very important for you.

If you don’t have basic knowledge of SQL JOIN, you need not worry about it. Here I will explain everything related to it.

sql join 3 tables

Join 3 Tables in SQL

SQL JOIN has four joining keywords like INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN. So, You will learn to join 3 tables using these keywords from the next step.

Important Points

To join 3 tables, You should know the following points –

  • All the 3 tables should be in a relationship with a foreign key.
  • Each table must have a common column.
  • The common column must contain the matching values.
  • a common column of the first tables must have a primary key and another common column of the second tables must have a foreign key.
  • datatype & name of the common column may be the same or different.
  • All 3 tables contain the same or the different numbers of rows or columns with some values.

Example –

To understand SQL join Query for 3 tables. You have to see an example. So, Let’s discuss it with the three tables like students , courses , subjects . Each table is related to each other with the Foreign keys.

Now, See the structure of the following tables.

Table Name – universities

university_id university_name
1001 SRM University
1002 Amity University
1003 Anna University
1004 Hindustan University

Table Name – students

This table will be joined to universities table based on a common column university_id .

student_id full_name gender university_id
201 Noor Khan Male 1001
202 Avneesh Mishra Male 1002
203 Monika Singh Female 1003
204 Aaliya Khan Female 1004
205 Sunil Kumar Male 1005
206 Mamta Gupta Female 1006
207 Rapson Jani Male 1007
208 Kundan Bharti Male 1008
209 Manmohan Singh Male 1009
210 Manisha Chaudhry Male 1010

Table Name – contacts

This table will be joined to students table based on a common column student_id

contact_id mobile_number email_address student_id
51 2222222222 aaaa222@gmail.com 201
52 5555555555 bbbb555@gmail.com 202
53 7777777777 cccc777@gmail.com 203
54 8888888888 dddd888@gmail.com 204
55 1010101010 eeee101@gmail.com 204
56 1212121212 ffff121@gmail.com 204
57 1313131313 gggg131@gmail.com 202
58 1414141414 iiii141@gmail.com 202
59 1515151515 jjjj151@gmail.com 2015

INNER JOIN 3 Tables

If you use the INNER JOIN keyword with the select statement, It will return a new result table by joining the above three tables with the matching records of each table

You can join 3 tables using the following INNER JOIN syntax –

full_name gender mobile_number email_address university_name
Noor Khan Male 2222222222 aaaa222@gmail.com SRM University
Avneesh Mishra Male 5555555555 bbbb555@gmail.com Amity University
Monika Singh Female 7777777777 cccc777@gmail.com Anna University
Aaliya Khan Female 8888888888 dddd888@gmail.com Hindustan University
Aaliya Khan Female 1010101010 eeee101@gmail.com Hindustan University
Aaliya Khan Female 1212121212 ffff121@gmail.com Hindustan University
Avneesh Mishra Male 1313131313 gggg131@gmail.com Amity University
Avneesh Mishra Male 1414141414 iiii141@gmail.com Amity University

LEFT JOIN 3 Tables

If you use the LEFT JOIN keyword with the select statement, It will return a new result table by joining the above three tables with all the records of left the table and matching values of the right tables.

You can join 3 tables using the following INNER JOIN syntax –

full_name gender mobile_number email_address university_name
Noor Khan Male 2222222222 aaaa222@gmail.com SRM University
Avneesh Mishra Male 5555555555 bbbb555@gmail.com Amity University
Monika Singh Female 7777777777 cccc777@gmail.com Anna University
Aaliya Khan Female 8888888888 dddd888@gmail.com Hindustan University
Aaliya Khan Female 1010101010 eeee101@gmail.com Hindustan University
Aaliya Khan Female 1212121212 ffff121@gmail.com Hindustan University
Avneesh Mishra Male 1313131313 gggg131@gmail.com Amity University
Avneesh Mishra Male 1414141414 iii141@gmail.com Amity University
Sunil Kumar Male NULL NULL Hindustan University
Mamta Gupta Female NULL NULL Hindustan University
Rapson Jani Male NULL NULL SRM University
Kundan Bharti Male NULL NULL SRM University

RIGHT JOIN 3 Tables

If you use the RIGHT JOIN keyword with the select statement, It will return a new result table by joining the above three tables with all the records of right the table and matching values of the left tables.

You can join 3 tables using the following INNER JOIN syntax –

full_name gender mobile_number email_address university_name
Noor Kha Male 2222222222 aaaa222@gmail.com SRM University
Avneesh Mishra Male 5555555555 bbbb555@gmail.com Amity University
Monika Singh Female 7777777777 cccc777@gmail.com Anna University
Aaliya Khan Female 8888888888 dddd888@gmail.com Hindustan University
Aaliya Khan Female 1010101010 eeee101@gmail.com Hindustan University
Aaliya Khan Female 1212121212 ffff121@gmail.com Hindustan University
Avneesh Mishra Male 1313131313 gggg131@gmail.com Amity University
Avneesh Mishra Male 1414141414 iiii141@gmail.com Amity University
NULL NULL 1515151515 jjjj151@gmail.com NULL

FULL JOIN 3 Tables

If you use the RIGHT JOIN keyword with the select statement, It will return a new result table by joining the above three tables with all the records of right the table and left tables.

You can join 3 tables using the following INNER JOIN syntax –

full_name gender mobile_number email_address university_name
Noor Khan Male 2222222222 aaaa222@gmail.com SRM University
Avneesh Mishra Male 5555555555 bbbb555@gmail.com Amity University
Monika Singh Female 7777777777 cccc777@gmail.com Anna University
Aaliya Khan Female 8888888888 dddd888@gmail.com Hindustan University
Aaliya Khan Female 1010101010 eeee101@gmail.com Hindustan University
Aaliya Khan Female 1212121212 ffff121@gmail.com Hindustan University
Avneesh Mishra Male 1313131313 gggg131@gmail.com Amity University
Avneesh Mishra Male 1414141414 iiii141@gmail.com Amity University
Sunil Kuma Male NULL NULL Hindustan University
Mamta Gupta Female NULL NULL Hindustan University
Rapson Jani Male NULL NULL SRM University
Kundan Bharti Male NULL NULL SRM University
Manmohan Singh Male NULL NULL NULL
Manisha Chaudhry Male NULL NULL NULL
NULL NULL 1515151515 jjjj151@gmail.com NULL

Join 3 Tables with Conditions

Here, you will learn to join 3 tables with different conditions using the INNER JOIN keyword. Once you learn it, you will definitely know to use LEFT JOIN, RIGHT JOIN & FULL JOIN keyword.

Join 3 Tables with WHERE Clause

If you want to select those records that have a gender value is ‘male’ then you can join 3 tables with where clause.

Join 3 Tables with ORDER BY Clause

If you want to select records based on full_name in alphabetical order then you can join 3 tables with ORDER BY clause.

Join 3 Tables with GROUP BY clause

If you want to count records by grouping gender then you can join 3 tables with the GROUP BY clause

How to Join 3 Tables in SQL

To join 3 tables, you have to configure the following points –

  • First of all, make sure that the SQL package is installed in your computer
  • Create a MySQL Database
  • Create 3 tables in MySQL database
  • Insert some records in all three tables
  • Join all three 3 tables using INNER JOIN, LEFT JOIN, RIGHT JOIN, or FULL JOIN.

Query –

Using INNER JOIN Command

Run the following command to join all three tables using INNER JOIN.

Note – You have created a database & tables in the previous step. Now, you need not create it again.

Using LEFT JOIN Command

Run the following command to join all three tables using LEFT JOIN.

Using Right JOIN Command

Run the following command to join all three tables using the RIGHT JOIN.

Using FULL JOIN Command

Run the following command to join all three tables using the RIGHT JOIN.

Tutorial Summary

Dear Developer, I have this tutorial with complete information. I hope that You have learned to join 3 tables using SQL. Now you can join any type of table.

If you have any questions, Kindly ask me through the comment box. Even, you should share this tutorial with your friends.

Hey there, Welcome to CodingStatus. My Name is Md Nurullah from Bihar, India. I’m a Software Engineer. I have been working in the Web Technology field for 3 years. Here, I blog about Web Development & Designing. Even I help developers to build the best Web Applications.

Join 3 Tables in SQL

In SQL, you can join three tables or more by adding another join after the first one.

You can also run nested joins by specifying one join as the join condition for another.

Syntax

The most common way of joining three tables goes something like this:

This uses an inner join, but you can specify your desired join type as with any other join. You can also combine join types if required (example below).

You can also use nested joins by specifying one join as the join condition for another join. Like this:

Sample Data – The 3 Tables

Suppose we have the following three tables.

The Customers table:

The Cities table:

The StateProvinces table:

Example 1 – Inner Join 3 Tables

The most popular join type is the inner join, so we’ll start with that.

Here’s an example of joining the above three tables with two inner joins.

Example 2 – Combining Join Types

You can combine join types when joining three or more tables.

Here’s an example of combining an inner join with a left join.

In this case, we have a city (Peeples Valley) that doesn’t yet have any customers.

The reason we can now see that information is because the left join returns rows that have data in the left table, even if there’s no matching rows in the left table.

The previous example that combined two inner joins didn’t return this row, because inner joins discard unmatched rows from both tables. It only returns rows when there is at least one row in both tables that match the join condition.

New Sample Data – 3 Different Tables

For the remaining examples, we’ll use the following tables.

The PetTypes table:

The Owners table:

  • The PetTypeId column of the Pets table is a foreign key of the PetTypeId of the PetTypes table (which is the primary key of that table).
  • The OwnerId column of the Pets table is a foreign key of the OwnerId column of the Owners table.

Example 3 – Left Join 3 Tables

Let’s do a three-table join using two left joins.

Here’s an example of running two left joins against those tables.

Here, we have a pet owner that doesn’t have a pet. We can verify that by looking at the Pets.OwnerId column, and seeing that there’s no value that corresponds with Woody Eastwood’s OwnerId in the Owners table.

Example 4 – Right Join 3 Tables

The right join is the opposite of the left join. Here’s an example using the same three tables.

This time we got an extra pet type ( Rabbit ), but not the extra owner. This is because right joins return rows that have data in the right table, even if there’s no matching rows in the left table.

By the way, the reason the last PetOwner is not NULL (like last the PetName is) is because it’s a result of a string concatenation. I used the T-SQL CONCAT() function to concatenate the owner’s first and last names.

Example 5 – Full Join 3 Tables

The full join is like having a left and right join in one. It returns all rows, as long as there’s matching data in one of the tables.

This time we get a combination of the results that we got in the previous two examples.

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

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