 Приєднання 2 Таблиць
Приєднання 2 Таблиць
We've got the attention of a company that owns a small online store. They have 2 tables that are related to each other. The first table contains information about the products sold in the online store.
Here's what the product table looks like:
The second table contains product categories on the website, along with a brief description for each category.
Here's what the category table looks like:
Our first task is to join these two tables to find out how many products are in each category. We'll use a JOIN statement to achieve this.
Before diving into the task, let's understand what a JOIN statement is and how it works.
To join two tables, they need to share a common column. Let's see how JOIN works using the employees and department tables. Their common column is employees.department and departments.name.
Note
When writing columns from these tables, start with the table name, add a dot, and then the column name. This helps keep the code clear, especially when tables have columns with the same name. It tells SQL exactly which table and column you mean.
Щоб об'єднати 2 таблиці, вони повинні мати спільну колонку між собою. Розглянемо використання JOIN, на прикладі таблиць employees і department. Нагадаю вам, що їх спільною колонкою є employees.department та departments.name.
Примітка
Зверніть увагу, як я написав колонки з цих таблиць. Спочатку я пишу назву таблиці, потім ставлю крапку і назву колонки. Коли ми використовуємо більш ніж одну таблицю у запиті, нам потрібно вказати таблицю, з якої ми беремо колонку, щоб код був читабельним. Також, у випадку коли таблиці мають колонки однакових назв, нам потрібно, щоб SQL зрозуміло, до якої таблиці та колонки ми звертаємося.
1234SELECT department.type, SUM(employees.salary) AS total_salary FROM employees JOIN department ON employees.department = department.name GROUP BY department.type
Let's break down how we used JOIN in our query:
- In the SELECTpart, we list the columns we want from both tables, making sure to include the table name for clarity;
- In the JOINpart, we specify the table to join and the common column that links them. Here, it'semployees.departmentanddepartment.name;
- We then group the data by typeto calculate the total salary using theSUM()function.
If this seems complex, here's a simple syntax for using JOIN:
Давайте крок за кроком зрозуміємо, що ми зробили і як ми використовували JOIN:
- У розділі SELECTми вказуємо колонки, які нам потрібно отримати з двох таблиць, зазначаючи назву таблиці, до якої належить колонка;
- У розділі JOINми вказуємо таблицю, яку хочемо приєднати, а потім вказуємо спільну колонку. У нашому випадку, цеemployees.departmentтаdepartment.name;
- Потім ми агрегуємо дані за type(оскільки у розділіSELECTми маємо агрегатну функціюSUM()для знаходження загальної заробітної плати) та отримуємо цікавий нам результат.
Запит може виглядати складним, отже подивімось на загальний синтаксис використання JOIN:
Note
Unlike the
UNIONclause, theJOINstatement lets us combine entire tables, not just the columns they share. Plus, withJOIN, there's no need for subqueries like withUNION.
Swipe to start coding
Your need to join the two tables: category and product. The common columns for these two tables are product.category_id and category.id.
Your task is to find the total amount of products in each category. To do this, you need to calculate the sum of the product.amount column.
Use the alias total_amount for this column.
At the end of your query, sort the result by the total_amount column in ascending order.
In the response, you should have 2 columns: category.name and total.amount.
Brief Instructions
- Retrieve the category.namecolumn and the sum of theproduct.amountcolumn from theproducttable.
- Assign the alias total_amountto the second column.
- Join the categorytable using aJOINstatement.
- Match the tables on the common column product.category_id = category_id.
- Group the results by category.name.
- Sort the results by total_amount.
Рішення
Дякуємо за ваш відгук!
single
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
What are the different types of JOINs in SQL?
Can you explain how to join the product and category tables using SQL?
Why do we need to use table names before column names in JOIN queries?
Awesome!
Completion rate improved to 4 Приєднання 2 Таблиць
Приєднання 2 Таблиць
Свайпніть щоб показати меню
We've got the attention of a company that owns a small online store. They have 2 tables that are related to each other. The first table contains information about the products sold in the online store.
Here's what the product table looks like:
The second table contains product categories on the website, along with a brief description for each category.
Here's what the category table looks like:
Our first task is to join these two tables to find out how many products are in each category. We'll use a JOIN statement to achieve this.
Before diving into the task, let's understand what a JOIN statement is and how it works.
To join two tables, they need to share a common column. Let's see how JOIN works using the employees and department tables. Their common column is employees.department and departments.name.
Note
When writing columns from these tables, start with the table name, add a dot, and then the column name. This helps keep the code clear, especially when tables have columns with the same name. It tells SQL exactly which table and column you mean.
Щоб об'єднати 2 таблиці, вони повинні мати спільну колонку між собою. Розглянемо використання JOIN, на прикладі таблиць employees і department. Нагадаю вам, що їх спільною колонкою є employees.department та departments.name.
Примітка
Зверніть увагу, як я написав колонки з цих таблиць. Спочатку я пишу назву таблиці, потім ставлю крапку і назву колонки. Коли ми використовуємо більш ніж одну таблицю у запиті, нам потрібно вказати таблицю, з якої ми беремо колонку, щоб код був читабельним. Також, у випадку коли таблиці мають колонки однакових назв, нам потрібно, щоб SQL зрозуміло, до якої таблиці та колонки ми звертаємося.
1234SELECT department.type, SUM(employees.salary) AS total_salary FROM employees JOIN department ON employees.department = department.name GROUP BY department.type
Let's break down how we used JOIN in our query:
- In the SELECTpart, we list the columns we want from both tables, making sure to include the table name for clarity;
- In the JOINpart, we specify the table to join and the common column that links them. Here, it'semployees.departmentanddepartment.name;
- We then group the data by typeto calculate the total salary using theSUM()function.
If this seems complex, here's a simple syntax for using JOIN:
Давайте крок за кроком зрозуміємо, що ми зробили і як ми використовували JOIN:
- У розділі SELECTми вказуємо колонки, які нам потрібно отримати з двох таблиць, зазначаючи назву таблиці, до якої належить колонка;
- У розділі JOINми вказуємо таблицю, яку хочемо приєднати, а потім вказуємо спільну колонку. У нашому випадку, цеemployees.departmentтаdepartment.name;
- Потім ми агрегуємо дані за type(оскільки у розділіSELECTми маємо агрегатну функціюSUM()для знаходження загальної заробітної плати) та отримуємо цікавий нам результат.
Запит може виглядати складним, отже подивімось на загальний синтаксис використання JOIN:
Note
Unlike the
UNIONclause, theJOINstatement lets us combine entire tables, not just the columns they share. Plus, withJOIN, there's no need for subqueries like withUNION.
Swipe to start coding
Your need to join the two tables: category and product. The common columns for these two tables are product.category_id and category.id.
Your task is to find the total amount of products in each category. To do this, you need to calculate the sum of the product.amount column.
Use the alias total_amount for this column.
At the end of your query, sort the result by the total_amount column in ascending order.
In the response, you should have 2 columns: category.name and total.amount.
Brief Instructions
- Retrieve the category.namecolumn and the sum of theproduct.amountcolumn from theproducttable.
- Assign the alias total_amountto the second column.
- Join the categorytable using aJOINstatement.
- Match the tables on the common column product.category_id = category_id.
- Group the results by category.name.
- Sort the results by total_amount.
Рішення
Дякуємо за ваш відгук!
single